Python quickstart for programmers: Python Kung Fu

14,072 views

Published on

A quick introduction to Python aimed at programmers.

Published in: Technology, Business

Python quickstart for programmers: Python Kung Fu

  1. 1. Python Kung Fu
  2. 2. The Zen of Python <ul><li>Beautiful is better than ugly. </li></ul><ul><li>Explicit is better than implicit. </li></ul><ul><li>Simple is better than complex. </li></ul><ul><li>Complex is better than complicated. </li></ul><ul><li>Flat is better than nested. </li></ul><ul><li>Sparse is better than dense. </li></ul><ul><li>Readability counts. </li></ul><ul><li>Special cases aren't special enough to break the rules. </li></ul>
  3. 3. The Zen of Python cont. <ul><li>Although practicality beats purity. </li></ul><ul><li>Errors should never pass silently. </li></ul><ul><li>Unless explicitly silenced. </li></ul><ul><li>In the face of ambiguity, refuse the temptation to guess. </li></ul><ul><li>There should be one-- and preferably only one --obvious way to do it. </li></ul><ul><li>Although that way may not be obvious at first unless you're Dutch. </li></ul><ul><li>Now is better than never. </li></ul>
  4. 4. The Zen of Python cont. <ul><li>Although never is often better than *right* now. </li></ul><ul><li>If the implementation is hard to explain, it's a bad idea. </li></ul><ul><li>If the implementation is easy to explain, it may be a good idea. </li></ul><ul><li>Namespaces are one honking great idea -- let's do more of those! </li></ul>
  5. 5. Uses <ul><li>Prototyping </li></ul><ul><li>Glue language </li></ul><ul><li>Web development </li></ul><ul><li>System administration </li></ul><ul><li>Desktop applications </li></ul><ul><li>Games </li></ul><ul><li>Everything! Ok not everything but almost </li></ul>
  6. 6. Hello World <ul><li>print(''Hello world'') </li></ul><ul><ul><li>Python 3 </li></ul></ul><ul><li>print ''Hello World'' </li></ul><ul><ul><li>Python 2.6 </li></ul></ul><ul><li>Notice the missing ; </li></ul>
  7. 7. Comments <ul><li>#This is a comment </li></ul>
  8. 8. types <ul><li>Numeric </li></ul><ul><ul><li>Long or int e.g. 1 </li></ul></ul><ul><ul><li>Float e.g. 2.5 </li></ul></ul><ul><ul><li>Complex e.g. 3 + 4j </li></ul></ul><ul><li>Boolean </li></ul><ul><ul><li>True </li></ul></ul><ul><ul><li>False </li></ul></ul><ul><ul><li>or </li></ul></ul><ul><ul><li>and </li></ul></ul>
  9. 9. Types cont. <ul><li>Strings </li></ul><ul><ul><li>'I am a string' </li></ul></ul><ul><ul><li>“Im also a string“ </li></ul></ul><ul><li>Sequences </li></ul><ul><ul><li>Lists (or array) [0,1,3] [2,5,“woo hoo“] </li></ul></ul><ul><ul><li>Tuples (1,2,3) </li></ul></ul>
  10. 10. Types cont. <ul><li>Collections </li></ul><ul><ul><li>Dictionary (or hash or map) </li></ul></ul><ul><ul><ul><li>{123:“mi casa“, 234:“casa de pepito} </li></ul></ul></ul><ul><ul><li>Set </li></ul></ul><ul><ul><ul><li>set('hola') </li></ul></ul></ul><ul><li>Additional types </li></ul><ul><ul><li>unicode, buffer, xrange, frozenset, file </li></ul></ul>
  11. 11. Assingments <ul><li>id = 10 </li></ul><ul><li>Watch out for aliasing! </li></ul>
  12. 12. Operators <ul><li>Cool new stuff </li></ul><ul><ul><li>** </li></ul></ul><ul><ul><li>// </li></ul></ul><ul><li>Sorry no ++ or –- </li></ul><ul><li>The rest is about the same </li></ul><ul><li>Including this </li></ul><ul><ul><li>+= -= *= /= %= **= //= </li></ul></ul>
  13. 13. BIFs <ul><li>y = abs( x ) </li></ul><ul><li>z = complex( r, i ) </li></ul>
  14. 14. modules <ul><li>from math import * </li></ul><ul><li>from math import sqrt </li></ul>
  15. 15. Objects and Methods <ul><li>Construction </li></ul><ul><ul><li>today = date( 2006, 8, 25 ) </li></ul></ul><ul><ul><li>Notice the missing 'new' </li></ul></ul><ul><li>Methods </li></ul><ul><ul><li>which_day = today.weekday() </li></ul></ul>
  16. 16. Cooler printing <ul><li>print &quot;The sum of %d and %d is %f &quot; % (a, b, sum) </li></ul><ul><li>print ''The sum of '' + a + '' and '' + b '' is '' + sum </li></ul>
  17. 17. Selection statements <ul><li>if value < 0: </li></ul><ul><ul><li>print 'Im negative' </li></ul></ul><ul><li>elif value == 0: </li></ul><ul><ul><li>print 'Im zero' </li></ul></ul><ul><li>else </li></ul><ul><ul><li>print 'Im positive' </li></ul></ul>
  18. 18. Comparison <ul><li>Your usual stuff </li></ul><ul><ul><li>< > <= >= == != </li></ul></ul>
  19. 19. Comparison cont. <ul><li>str1 = &quot;Abc Def&quot; </li></ul><ul><li>str2 = &quot;Abc def&quot; </li></ul><ul><li>if str1 == str2 : </li></ul><ul><li>print &quot;Equal!!&quot; </li></ul><ul><li>else : </li></ul><ul><li>print &quot;Not Equal!!&quot; </li></ul>
  20. 20. Comparison cont. <ul><li>name1 = &quot;Smith, John&quot;; </li></ul><ul><li>name2 = &quot;Smith, Jane&quot;; </li></ul><ul><li>if name1 < name2 : </li></ul><ul><li>print &quot;Name1 comes first.&quot; </li></ul><ul><li>elif name1 > name2 : </li></ul><ul><li>print &quot;Name2 comes first.&quot; </li></ul><ul><li>else : </li></ul><ul><li>print &quot;The names are the same.&quot; </li></ul>
  21. 21. Stuff that rules <ul><li>if &quot;Smith&quot; in name1 : </li></ul><ul><li>print name1 </li></ul>
  22. 22. Null reference <ul><li># The is operator along with None can tests for null references. </li></ul><ul><li>result = name1 is None </li></ul><ul><li>result2 = name1 == None </li></ul><ul><li>Watch out, ther is no Null! </li></ul>
  23. 23. Repetition Statements <ul><li>theSum = 0 </li></ul><ul><li>i = 1 </li></ul><ul><li>while i <= 100: </li></ul><ul><li>theSum = theSum + i </li></ul><ul><li>i = i + 1 </li></ul><ul><li>print &quot;The sum = &quot;, theSum </li></ul>
  24. 24. Repetition Statements cont. <ul><li>for <loop-var> in <object> : </li></ul><ul><li><statement-block> </li></ul><ul><li>for i in xrange( 1, 11 ) : </li></ul><ul><li>print i </li></ul>
  25. 25. Cool tricks <ul><li>for i in xrange( 10, 0, -1 ) : </li></ul><ul><li>print i </li></ul>
  26. 26. Iterating from zero <ul><li>for i in xrange( 20 ) </li></ul><ul><li>print i </li></ul>
  27. 27. Functions <ul><li>def sumRange( first, last ) : </li></ul><ul><li>total = 0 </li></ul><ul><li>i = first </li></ul><ul><li>while i <= last : </li></ul><ul><li>total = total + i </li></ul><ul><li>i = i + 1 </li></ul><ul><li>return total </li></ul>
  28. 28. Default values <ul><li>def sumRange2( first, last, step = 1 ) : </li></ul><ul><li>total = 0 </li></ul><ul><li>i = first </li></ul><ul><li>while i <= last : </li></ul><ul><li>total = total + i </li></ul><ul><li>i = i + step </li></ul><ul><li>return total </li></ul>
  29. 29. Clear readable code! <ul><li>theSum = sumRange2( last = 100, step = 3, first = 1 ) </li></ul>
  30. 30. Modules and namespaces
  31. 31. List basics <ul><li>Creating </li></ul><ul><ul><li>gradeList = [ 85, 90, 87, 65, 91 ] </li></ul></ul><ul><li>To demonstrate element access in Python, consider the following statements </li></ul><ul><li>print &quot;Forward:&quot;, gradeList[ 0 ],gradeList[ 3 ] </li></ul><ul><li>print &quot;Reverse:&quot;, gradeList[ -1 ],gradeList[ -3 ] </li></ul><ul><li>which produces the following output </li></ul><ul><li>Forward: 85 65 </li></ul><ul><li>Reverse: 91 87 </li></ul>
  32. 32. List length <ul><li>theLength = len( gradeList ) </li></ul><ul><li>print &quot;The list contains %d elements.&quot; % theLength </li></ul>
  33. 33. Java sucks <ul><li>// Java array printing. </li></ul><ul><li>System.out.print( &quot;[&quot; ); </li></ul><ul><li>for( int i = 0; i < gradeList.length; i++ ) { </li></ul><ul><li>System.out.print( gradeList[ i ] ); </li></ul><ul><li>if( i < gradeList.length-1 ) </li></ul><ul><li>System.out.print( &quot;, &quot; ); </li></ul><ul><li>} </li></ul><ul><li>System.out.println( &quot;]&quot; ) </li></ul>
  34. 34. Python rules! <ul><li>print gradeList </li></ul>
  35. 35. Python lists rule <ul><li>Don't worry about list lengths. The interpreter will take care of that for you. </li></ul><ul><li>I case you want to simulate a classic array you can do this. </li></ul><ul><ul><li>histogram = [ 0 ] * 10 </li></ul></ul>
  36. 36. List iteration <ul><li>total = 0 </li></ul><ul><li>for value in valueList : </li></ul><ul><li>total = total + value </li></ul><ul><li>avg = float( total ) / len( valueList ) </li></ul><ul><li>print &quot;The average value = %6.2f&quot; % avg </li></ul>
  37. 37. Tuples, tuples. Immutable = safety <ul><li>t = ( 0, 2, 4 ) # 3 element tuple </li></ul><ul><li>a = ( 2, ) # 1 element tuple </li></ul><ul><li>b = ( 'abc', 1, 4.5, 5 ) # 4 element mixed tuple </li></ul><ul><li>c = ( 0, ( 'a', 'b' ) ) # nested tuple </li></ul>
  38. 38. List ninja skills <ul><li>import random </li></ul><ul><li># Create the empty list. </li></ul><ul><li>valueList = [] </li></ul><ul><li># Build the list of random values. </li></ul><ul><li>for i in range( 1000 ) : </li></ul><ul><li>valueList.append( random.random() ) </li></ul>
  39. 39. hyadoken! <ul><li>listA = [ 0, 1, 2, 3 ] </li></ul><ul><li>listB = listA.extend( [ 4, 5, 6 ] ) </li></ul><ul><li>print listB </li></ul>
  40. 40. Atreketroken <ul><li>values = [ 0, 1, 2, 3, 4 ] </li></ul><ul><li>values.insert( 1, 8 ) </li></ul><ul><li>print values </li></ul>
  41. 41. More classic stuff <ul><li>list.insert( atIndex, value ) </li></ul>
  42. 42. Removing items <ul><li>x = theList.pop( 1 ) </li></ul><ul><li>print &quot;list =&quot;, theList </li></ul><ul><li>print &quot;x =&quot;, x </li></ul>
  43. 43. More removal <ul><li>theList = [ 10, 11, 12, 13 ] </li></ul><ul><li>theList.remove( 11 ) </li></ul><ul><li>print theList # prints [10, 12, 13] </li></ul>
  44. 44. Searching <ul><li>theList = [ 10, 11, 12, 13 ] </li></ul><ul><li>pos = theList.index( 13 ) </li></ul><ul><li>print pos </li></ul><ul><li># prints 3 </li></ul>
  45. 45. This isn't funny anymore <ul><li>// Java item search. </li></ul><ul><li>int i = 0; </li></ul><ul><li>while( i < gradeList.length ) { </li></ul><ul><li>if( gradeList[ i ] == 100 ) </li></ul><ul><li>System.out.println( &quot;Someone received at least one &quot; </li></ul><ul><li>+ &quot; perfect score.&quot; ); </li></ul><ul><li>i++; </li></ul><ul><li>} </li></ul>
  46. 46. Haha <ul><li>if 100 in gradeList : </li></ul><ul><li>print &quot;Student received at least one perfect score.&quot; </li></ul>
  47. 47. Lost your index? <ul><li>print gradeList.index( 90 ) </li></ul>
  48. 48. Min max <ul><li>print &quot;The minimum value = &quot;, min( valueList ) </li></ul><ul><li>print &quot;The maximim value = &quot;, max( valueList ) </li></ul>
  49. 49. List concatenation <ul><li>listA = [ 1, 2, 3 ] </li></ul><ul><li>listB = [ 8, 9 ] </li></ul><ul><li>which can be concatenated to produce a third list. If we execute the statements </li></ul><ul><li>bigList = listA + listB </li></ul><ul><li>print bigList </li></ul>
  50. 50. List duplication <ul><li>listX = [ 1, 2, 3 ] </li></ul><ul><li>listY = listX + [] </li></ul><ul><li>listY[0] = 0 </li></ul><ul><li>print &quot;X:&quot;, listX </li></ul><ul><li>print &quot;y:&quot;, listY </li></ul><ul><li>Will now produce the following since listY now references a new list which happens to be a duplicate copy of listX. </li></ul>
  51. 51. Reverse <ul><li>theList = [ 10, 11, 12, 13 ] </li></ul><ul><li>theList.reverse() </li></ul><ul><li>print theList </li></ul><ul><li># prints [13, 12, 11, 10] </li></ul>
  52. 52. Replication <ul><li>intList = [ 0, 1, 2, 3, 4 ] * 25 </li></ul>
  53. 53. The coolest shit ever <ul><li>The following are common ways to describe lists (or sets, or tuples, or vectors) in mathematics. </li></ul><ul><li>S = {x² : x in {0 ... 9}} </li></ul><ul><li>V = (1, 2, 4, 8, ..., 2¹²) </li></ul><ul><li>M = {x | x in S and x even} </li></ul>
  54. 54. Wuahahahha! <ul><li>>>> S = [x**2 for x in range(10)] </li></ul><ul><li>>>> V = [2**i for i in range(13)] </li></ul><ul><li>>>> M = [x for x in S if x % 2 == 0] </li></ul>
  55. 55. OO programming <ul><li># point.py </li></ul><ul><li># Defines a class to represent two-dimensional discrete points. </li></ul><ul><li>class Point : </li></ul><ul><li>def __init__( self, x = 0, y = 0 ) : </li></ul><ul><li>self.xCoord = x </li></ul><ul><li>self.yCoord = y </li></ul>
  56. 56. cont. <ul><li>def __str__( self ) : </li></ul><ul><li>return &quot;(&quot; + str( self.yCoord ) + &quot;, &quot; + </li></ul><ul><li>str( self.yCoord ) + &quot;)&quot; </li></ul><ul><li>def getX( self ) : </li></ul><ul><li>return self.XCoord </li></ul>
  57. 57. cont. <ul><li>def getY( self ) : </li></ul><ul><li>return self.yCoord </li></ul><ul><li>def shift( self, xInc, yInc ) : </li></ul><ul><li>self.xCoord += xInc </li></ul><ul><li>self.yCoord += yInc </li></ul>
  58. 58. Object instantiation <ul><li>from point import * </li></ul><ul><li>pointA = Point( 5, 7 ) </li></ul><ul><li>pointB = Point() </li></ul>
  59. 59. Private members and methods <ul><li>Private </li></ul><ul><ul><li>def __helpermethod </li></ul></ul><ul><ul><li>def __privatefield </li></ul></ul>
  60. 60. Inheritance <ul><li>class DerivedClassName(BaseClassName): </li></ul><ul><li><statement-1> </li></ul><ul><li>. </li></ul><ul><li>. </li></ul><ul><li>. </li></ul><ul><li><statement-N> </li></ul>
  61. 61. Stuff you maybe haven't tried <ul><li>Multiple Inheritance </li></ul><ul><li>Operator overloading </li></ul>
  62. 62. Extra stuff you should know <ul><li>There are no 'interfaces' but you can emulate them. </li></ul><ul><li>There is no 'abstract' or 'virtual' keyword but you can emulate this behaviour. </li></ul><ul><li>Abstract base classes serve as THE alternative to interfaces. Python ABC's are somewhat similar to C++ ABC's </li></ul><ul><li>Duck typing </li></ul>
  63. 63. If it walks like a duck and quacks like a duck, I would call it a duck. <ul><li>function calculate(a, b, c) => return (a+b)*c </li></ul><ul><li>example1 = calculate (1, 2, 3) </li></ul><ul><li>example2 = calculate ([1, 2, 3], [4, 5, 6], 2) </li></ul><ul><li>example3 = calculate ('apples ', 'and oranges, ', 3) </li></ul><ul><li>print to_string example1 </li></ul><ul><li>print to_string example2 </li></ul><ul><li>print to_string example3 </li></ul>
  64. 64. Ta tan! <ul><li>9 </li></ul><ul><li>[1, 2, 3, 4, 5, 6, 1, 2, 3, 4, 5, 6] </li></ul><ul><li>apples and oranges, apples and oranges, apples and oranges, </li></ul>
  65. 65. Conclusion <ul><li>Thus, duck typing allows polymorphism without inheritance. The only requirement that function calculate needs in its variables is having the &quot;+&quot; and the &quot;*&quot; methods </li></ul>
  66. 66. Exceptions <ul><li>try: </li></ul><ul><li>myList = [ 12, 50, 5, 17 ] </li></ul><ul><li>print myList[ 4 ] </li></ul><ul><li>except IndexError: </li></ul><ul><li>print &quot;Error: Index out of range.&quot; </li></ul>
  67. 67. Raising exceptions <ul><li>def min( value1, value2 ) : </li></ul><ul><li>if value1 == None or value2 == None : </li></ul><ul><li>raise TypeError </li></ul><ul><li>if value1 < value2 : </li></ul><ul><li>return value1 </li></ul><ul><li>else: </li></ul><ul><li>return value2 </li></ul>
  68. 68. Black belt python <ul><li>Class factories </li></ul><ul><li>Function factories </li></ul><ul><li>Functional programming </li></ul><ul><li>Generators </li></ul><ul><li>Advanced list idioms </li></ul><ul><li>Tons of other tricks </li></ul>
  69. 69. Python Implementations <ul><li>CPython 2.6 and 3.0 </li></ul><ul><li>CPython with Psyco </li></ul><ul><li>Jython </li></ul><ul><li>IronPython </li></ul><ul><li>PyPy </li></ul><ul><li>Stackless Python </li></ul><ul><li>and more... </li></ul>

×