Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
SlideShare a Scribd company logo

1

Python Kung Fu

2

The Zen of Python Beautiful is better than ugly. Explicit is better than implicit. Simple is better than complex. Complex is better than complicated. Flat is better than nested. Sparse is better than dense. Readability counts. Special cases aren't special enough to break the rules.

3

The Zen of Python cont. Although practicality beats purity. Errors should never pass silently. Unless explicitly silenced. In the face of ambiguity, refuse the temptation to guess. There should be one-- and preferably only one --obvious way to do it. Although that way may not be obvious at first unless you're Dutch. Now is better than never.

4

The Zen of Python cont. Although never is often better than *right* now. If the implementation is hard to explain, it's a bad idea. If the implementation is easy to explain, it may be a good idea. Namespaces are one honking great idea -- let's do more of those!

5

Uses Prototyping Glue language Web development System administration Desktop applications Games Everything! Ok not everything but almost

6

Hello World print(''Hello world'') Python 3 print ''Hello World'' Python 2.6 Notice the missing ;

7

Comments #This is a comment

8

types Numeric Long or int e.g. 1 Float e.g. 2.5 Complex e.g. 3 + 4j Boolean True  False or and

9

Types cont. Strings 'I am a string' “Im also a string“ Sequences Lists (or array)  [0,1,3] [2,5,“woo hoo“] Tuples (1,2,3)

10

Types cont. Collections Dictionary (or hash or map)  {123:“mi casa“, 234:“casa de pepito} Set set('hola') Additional types unicode, buffer, xrange, frozenset, file

11

Assingments id = 10 Watch out for aliasing!

12

Operators Cool new stuff ** // Sorry no ++ or –- The rest is about the same Including this +=  -=  *=  /=  %=  **=  //=

13

BIFs y = abs( x ) z = complex( r, i )

14

modules from math import * from math import sqrt

15

Objects and Methods Construction today = date( 2006, 8, 25 ) Notice the missing 'new' Methods which_day = today.weekday()

16

Cooler printing print "The sum of %d and %d is %f" % (a, b, sum) print ''The sum of  '' + a + '' and '' + b '' is '' + sum

17

Selection statements if  value < 0: print 'Im negative' elif value == 0: print 'Im zero' else print 'Im positive'

18

Comparison Your usual stuff <  >  <=  >=  ==  !=

19

Comparison cont. str1 = &quot;Abc Def&quot; str2 = &quot;Abc def&quot; if str1 == str2 : print &quot;Equal!!&quot; else : print &quot;Not Equal!!&quot;

20

Comparison cont. name1 = &quot;Smith, John&quot;; name2 = &quot;Smith, Jane&quot;; if name1 < name2 : print &quot;Name1 comes first.&quot; elif name1 > name2 : print &quot;Name2 comes first.&quot; else : print &quot;The names are the same.&quot;

21

Stuff that rules if &quot;Smith&quot; in name1 : print name1

22

Null reference # The is operator along with None can tests for null references. result = name1 is None result2 = name1 == None Watch out, ther is no Null!

23

Repetition Statements theSum = 0 i = 1 while i <= 100: theSum = theSum + i i = i + 1 print &quot;The sum = &quot;, theSum

24

Repetition Statements cont. for <loop-var> in <object> : <statement-block> for i in xrange( 1, 11 ) : print i

25

Cool tricks for i in xrange( 10, 0, -1 ) : print i

26

Iterating from zero for i in xrange( 20 ) print i

27

Functions def sumRange( first, last ) : total = 0 i = first while i <= last : total = total + i i = i + 1 return total

28

Default values def sumRange2( first, last, step = 1 ) : total = 0 i = first while i <= last : total = total + i i = i + step return total

29

Clear readable code! theSum = sumRange2( last = 100, step = 3, first = 1 )

30

Modules and namespaces

31

List basics Creating gradeList = [ 85, 90, 87, 65, 91 ] To demonstrate element access in Python, consider the following statements print &quot;Forward:&quot;, gradeList[ 0 ],gradeList[ 3 ] print &quot;Reverse:&quot;, gradeList[ -1 ],gradeList[ -3 ] which produces the following output Forward: 85 65 Reverse: 91 87

32

List length theLength = len( gradeList ) print &quot;The list contains %d elements.&quot; % theLength

33

Java sucks // Java array printing. System.out.print( &quot;[&quot; ); for( int i = 0; i < gradeList.length; i++ ) { System.out.print( gradeList[ i ] ); if( i < gradeList.length-1 ) System.out.print( &quot;, &quot; ); } System.out.println( &quot;]&quot; )

34

Python rules! print gradeList

35

Python lists rule Don't worry about list lengths. The interpreter will take care of that for you. I case you want to simulate a classic array you can do this. histogram = [ 0 ] * 10

36

List iteration total = 0 for value in valueList : total = total + value avg = float( total ) / len( valueList ) print &quot;The average value = %6.2f&quot; % avg

37

Tuples, tuples. Immutable = safety t = ( 0, 2, 4 )  # 3 element tuple a = ( 2, )  # 1 element tuple b = ( 'abc', 1, 4.5, 5 )  # 4 element mixed tuple c = ( 0, ( 'a', 'b' ) )  # nested tuple

38

List ninja skills import random # Create the empty list. valueList = [] # Build the list of random values. for i in range( 1000 ) : valueList.append( random.random() )

39

hyadoken! listA = [ 0, 1, 2, 3 ] listB = listA.extend( [ 4, 5, 6 ] ) print listB

40

Atreketroken values = [ 0, 1, 2, 3, 4 ] values.insert( 1, 8 ) print values

41

More classic stuff list.insert( atIndex, value )

42

Removing items x = theList.pop( 1 ) print &quot;list =&quot;, theList print &quot;x =&quot;, x

43

More removal theList = [ 10, 11, 12, 13 ] theList.remove( 11 ) print theList  # prints [10, 12, 13]

44

Searching theList = [ 10, 11, 12, 13 ] pos = theList.index( 13 ) print pos  # prints 3

45

This isn't funny anymore // Java item search. int i = 0; while( i < gradeList.length ) { if( gradeList[ i ] == 100 ) System.out.println( &quot;Someone received at least one &quot; + &quot; perfect score.&quot; ); i++; }

46

Haha if 100 in gradeList : print &quot;Student received at least one perfect score.&quot;

47

Lost your index? print gradeList.index( 90 )

48

Min max print &quot;The minimum value = &quot;, min( valueList ) print &quot;The maximim value = &quot;, max( valueList )

49

List concatenation listA = [ 1, 2, 3 ] listB = [ 8, 9 ]  which can be concatenated to produce a third list. If we execute the statements bigList = listA + listB print bigList

50

List duplication listX = [ 1, 2, 3 ] listY = listX + [] listY[0] = 0 print &quot;X:&quot;, listX print &quot;y:&quot;, listY Will now produce the following since listY now references a new list which happens to be a duplicate copy of listX.

51

Reverse theList = [ 10, 11, 12, 13 ] theList.reverse() print theList  # prints [13, 12, 11, 10]

52

Replication intList = [ 0, 1, 2, 3, 4 ] * 25

53

The coolest shit ever The following are common ways to describe lists (or sets, or tuples, or vectors) in mathematics. S = {x² : x in {0 ... 9}} V = (1, 2, 4, 8, ..., 2¹²) M = {x | x in S and x even}

54

Wuahahahha! >>> S = [x**2 for x in range(10)] >>> V = [2**i for i in range(13)] >>> M = [x for x in S if x % 2 == 0]

55

OO programming # point.py # Defines a class to represent two-dimensional discrete points. class Point : def __init__( self, x = 0, y = 0 ) : self.xCoord = x self.yCoord = y

56

cont. def __str__( self ) : return &quot;(&quot; + str( self.yCoord ) + &quot;, &quot; + str( self.yCoord ) + &quot;)&quot; def getX( self ) : return self.XCoord

57

cont. def getY( self ) : return self.yCoord def shift( self, xInc, yInc ) : self.xCoord += xInc self.yCoord += yInc

58

Object  instantiation from point import * pointA = Point( 5, 7 ) pointB = Point()

59

Private members and methods Private def __helpermethod def __privatefield

60

Inheritance class DerivedClassName(BaseClassName): <statement-1> . . . <statement-N>

61

Stuff you maybe haven't tried Multiple Inheritance Operator overloading

62

Extra stuff you should know There are no 'interfaces' but you can emulate them. There is no 'abstract' or 'virtual' keyword but you can emulate this behaviour. Abstract base classes serve as THE alternative to interfaces. Python ABC's are somewhat similar to C++ ABC's Duck typing

63

If it walks like a duck and quacks like a duck, I would call it a duck. function calculate(a, b, c) => return (a+b)*c example1 = calculate (1, 2, 3) example2 = calculate ([1, 2, 3], [4, 5, 6], 2) example3 = calculate ('apples ', 'and oranges, ', 3) print to_string example1 print to_string example2 print to_string example3

64

Ta tan! 9 [1, 2, 3, 4, 5, 6, 1, 2, 3, 4, 5, 6] apples and oranges, apples and oranges, apples and oranges,

65

Conclusion 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

66

Exceptions try: myList = [ 12, 50, 5, 17 ] print myList[ 4 ] except IndexError: print &quot;Error: Index out of range.&quot;

67

Raising exceptions def min( value1, value2 ) : if value1 == None or value2 == None : raise TypeError if value1 < value2 : return value1 else: return value2

68

Black belt python Class factories Function factories Functional programming Generators Advanced list idioms Tons of other tricks

69

Python Implementations CPython 2.6 and 3.0 CPython with Psyco Jython IronPython PyPy Stackless Python and more...

More Related Content

Python quickstart for programmers: Python Kung Fu

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