SlideShare a Scribd company logo
Python Kung Fu
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.
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.
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!
Uses Prototyping Glue language Web development System administration Desktop applications Games Everything! Ok not everything but almost
Hello World print(''Hello world'') Python 3 print ''Hello World'' Python 2.6 Notice the missing ;
Comments #This is a comment
types Numeric Long or int e.g. 1 Float e.g. 2.5 Complex e.g. 3 + 4j Boolean True  False or and
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)
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
Assingments id = 10 Watch out for aliasing!
Operators Cool new stuff ** // Sorry no ++ or –- The rest is about the same Including this +=  -=  *=  /=  %=  **=  //=
BIFs y = abs( x ) z = complex( r, i )
modules from math import * from math import sqrt
Objects and Methods Construction today = date( 2006, 8, 25 ) Notice the missing 'new' Methods which_day = today.weekday()
Cooler printing print "The sum of %d and %d is %f\n" % (a, b, sum) print ''The sum of  '' + a + '' and '' + b '' is '' + sum
Selection statements if  value < 0: print 'Im negative' elif value == 0: print 'Im zero' else print 'Im positive'
Comparison Your usual stuff <  >  <=  >=  ==  !=
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;
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;
Stuff that rules if &quot;Smith&quot; in name1 : print name1
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!
Repetition Statements theSum = 0 i = 1 while i <= 100: theSum = theSum + i i = i + 1 print &quot;The sum = &quot;, theSum
Repetition Statements cont. for <loop-var> in <object> : <statement-block> for i in xrange( 1, 11 ) : print i
Cool tricks for i in xrange( 10, 0, -1 ) : print i
Iterating from zero for i in xrange( 20 ) print i
Functions def sumRange( first, last ) : total = 0 i = first while i <= last : total = total + i i = i + 1 return total
Default values def sumRange2( first, last, step = 1 ) : total = 0 i = first while i <= last : total = total + i i = i + step return total
Clear readable code! theSum = sumRange2( last = 100, step = 3, first = 1 )
Modules and namespaces
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
List length theLength = len( gradeList ) print &quot;The list contains %d elements.&quot; % theLength
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; )
Python rules! print gradeList
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
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
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
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() )
hyadoken! listA = [ 0, 1, 2, 3 ] listB = listA.extend( [ 4, 5, 6 ] ) print listB
Atreketroken values = [ 0, 1, 2, 3, 4 ] values.insert( 1, 8 ) print values
More classic stuff list.insert( atIndex, value )
Removing items x = theList.pop( 1 ) print &quot;list =&quot;, theList print &quot;x =&quot;, x
More removal theList = [ 10, 11, 12, 13 ] theList.remove( 11 ) print theList  # prints [10, 12, 13]
Searching theList = [ 10, 11, 12, 13 ] pos = theList.index( 13 ) print pos  # prints 3
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++; }
Haha if 100 in gradeList : print &quot;Student received at least one perfect score.&quot;
Lost your index? print gradeList.index( 90 )
Min max print &quot;The minimum value = &quot;, min( valueList ) print &quot;The maximim value = &quot;, max( valueList )
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
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.
Reverse theList = [ 10, 11, 12, 13 ] theList.reverse() print theList  # prints [13, 12, 11, 10]
Replication intList = [ 0, 1, 2, 3, 4 ] * 25
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}
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]
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
cont. def __str__( self ) : return &quot;(&quot; + str( self.yCoord ) + &quot;, &quot; + str( self.yCoord ) + &quot;)&quot; def getX( self ) : return self.XCoord
cont. def getY( self ) : return self.yCoord def shift( self, xInc, yInc ) : self.xCoord += xInc self.yCoord += yInc
Object  instantiation from point import * pointA = Point( 5, 7 ) pointB = Point()
Private members and methods Private def __helpermethod def __privatefield
Inheritance class DerivedClassName(BaseClassName): <statement-1> . . . <statement-N>
Stuff you maybe haven't tried Multiple Inheritance Operator overloading
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
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
Ta tan! 9 [1, 2, 3, 4, 5, 6, 1, 2, 3, 4, 5, 6] apples and oranges, apples and oranges, apples and oranges,
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
Exceptions try: myList = [ 12, 50, 5, 17 ] print myList[ 4 ] except IndexError: print &quot;Error: Index out of range.&quot;
Raising exceptions def min( value1, value2 ) : if value1 == None or value2 == None : raise TypeError if value1 < value2 : return value1 else: return value2
Black belt python Class factories Function factories Functional programming Generators Advanced list idioms Tons of other tricks
Python Implementations CPython 2.6 and 3.0 CPython with Psyco Jython IronPython PyPy Stackless Python and more...

More Related Content

What's hot (20)

PDF
Python and sysadmin I
Guixing Bai
 
PDF
Python
대갑 김
 
PDF
python codes
tusharpanda88
 
PPTX
Python
Sameeksha Verma
 
PPTX
Python basics
NexThoughts Technologies
 
PDF
Declarative Thinking, Declarative Practice
Kevlin Henney
 
PPTX
GE8151 Problem Solving and Python Programming
Muthu Vinayagam
 
PPTX
Python programing
hamzagame
 
PPT
python.ppt
shreyas_test_1234
 
PPT
Introduction to Python - Part Two
amiable_indian
 
PDF
Python programming Workshop SITTTR - Kalamassery
SHAMJITH KM
 
PDF
Functions in python
Ilian Iliev
 
PDF
Introduction to python
Marian Marinov
 
PPTX
Introduction to Python and TensorFlow
Bayu Aldi Yansyah
 
PPTX
Introduction to the basics of Python programming (part 3)
Pedro Rodrigues
 
PDF
Python Tutorial
Eueung Mulyana
 
PDF
Python fundamentals - basic | WeiYuan
Wei-Yuan Chang
 
PPTX
Learn python - for beginners - part-2
RajKumar Rampelli
 
PDF
Python Cheat Sheet
Muthu Vinayagam
 
Python and sysadmin I
Guixing Bai
 
Python
대갑 김
 
python codes
tusharpanda88
 
Declarative Thinking, Declarative Practice
Kevlin Henney
 
GE8151 Problem Solving and Python Programming
Muthu Vinayagam
 
Python programing
hamzagame
 
python.ppt
shreyas_test_1234
 
Introduction to Python - Part Two
amiable_indian
 
Python programming Workshop SITTTR - Kalamassery
SHAMJITH KM
 
Functions in python
Ilian Iliev
 
Introduction to python
Marian Marinov
 
Introduction to Python and TensorFlow
Bayu Aldi Yansyah
 
Introduction to the basics of Python programming (part 3)
Pedro Rodrigues
 
Python Tutorial
Eueung Mulyana
 
Python fundamentals - basic | WeiYuan
Wei-Yuan Chang
 
Learn python - for beginners - part-2
RajKumar Rampelli
 
Python Cheat Sheet
Muthu Vinayagam
 

Viewers also liked (20)

PPT
Python 3000
Alexandro Colorado
 
PDF
Internet Programming With Python Presentation
AkramWaseem
 
PPT
Nagios Conference 2013 - Troy Lea - Leveraging and Understanding Performance ...
Nagios
 
ODP
Nagios Conference 2011 - William Leibzon - Nagios In Cloud Computing Environm...
Nagios
 
ODP
Nagios Conference 2014 - Troy Lea - Monitoring VMware Virtualization Using vMA
Nagios
 
PPT
Nagios Conference 2012 - Troy Lea - Custom Wizards, Components and Dashlets i...
Nagios
 
ODP
Nagios Conference 2014 - Shamas Demoret - Getting Started With Nagios XI
Nagios
 
PPTX
Nagios Conference 2012 - Nathan Vonnahme - Monitoring the User Experience
Nagios
 
ODP
Nagios Conference 2011 - Nicholas Scott - Nagios Performance Tuning
Nagios
 
PDF
Trevor McDonald - Nagios XI Under The Hood
Nagios
 
PPT
Bridging The Gap: Explaining OpenStack To VMware Administrators
Kenneth Hui
 
PDF
Automated Security Hardening with OpenStack-Ansible
Major Hayden
 
PDF
Training Ensimag OpenStack 2016
Bruno Cornec
 
PPTX
OpenStack + VMware: Everything You Need to Know (Kilo-edition)
Dan Wendlandt
 
ODP
Networking in OpenStack for non-networking people: Neutron, Open vSwitch and ...
Dave Neary
 
PDF
Openstack Neutron and SDN
inakipascual
 
PDF
OpenStack Neutron Tutorial
mestery
 
PDF
Ubuntu – Linux Useful Commands
University of Technology
 
PDF
(SCALE 12x) OpenStack vs. VMware - A System Administrator Perspective
StackStorm
 
PDF
My Top 10 slides on presentations
Alexei Kapterev
 
Python 3000
Alexandro Colorado
 
Internet Programming With Python Presentation
AkramWaseem
 
Nagios Conference 2013 - Troy Lea - Leveraging and Understanding Performance ...
Nagios
 
Nagios Conference 2011 - William Leibzon - Nagios In Cloud Computing Environm...
Nagios
 
Nagios Conference 2014 - Troy Lea - Monitoring VMware Virtualization Using vMA
Nagios
 
Nagios Conference 2012 - Troy Lea - Custom Wizards, Components and Dashlets i...
Nagios
 
Nagios Conference 2014 - Shamas Demoret - Getting Started With Nagios XI
Nagios
 
Nagios Conference 2012 - Nathan Vonnahme - Monitoring the User Experience
Nagios
 
Nagios Conference 2011 - Nicholas Scott - Nagios Performance Tuning
Nagios
 
Trevor McDonald - Nagios XI Under The Hood
Nagios
 
Bridging The Gap: Explaining OpenStack To VMware Administrators
Kenneth Hui
 
Automated Security Hardening with OpenStack-Ansible
Major Hayden
 
Training Ensimag OpenStack 2016
Bruno Cornec
 
OpenStack + VMware: Everything You Need to Know (Kilo-edition)
Dan Wendlandt
 
Networking in OpenStack for non-networking people: Neutron, Open vSwitch and ...
Dave Neary
 
Openstack Neutron and SDN
inakipascual
 
OpenStack Neutron Tutorial
mestery
 
Ubuntu – Linux Useful Commands
University of Technology
 
(SCALE 12x) OpenStack vs. VMware - A System Administrator Perspective
StackStorm
 
My Top 10 slides on presentations
Alexei Kapterev
 
Ad

Similar to Python quickstart for programmers: Python Kung Fu (20)

PDF
Python Variable Types, List, Tuple, Dictionary
Soba Arjun
 
PDF
Introduction to Python
UC San Diego
 
PDF
Beginning Python
Agiliq Solutions
 
PPT
ComandosDePython_ComponentesBasicosImpl.ppt
oscarJulianPerdomoCh1
 
PDF
python cheat sheat, Data science, Machine learning
TURAGAVIJAYAAKASH
 
PDF
2. Python Cheat Sheet.pdf
MeghanaDBengalur
 
PDF
beginners_python_cheat_sheet_pcc_all (1).pdf
ElNew2
 
PDF
Beginner's Python Cheat Sheet
Verxus
 
PPT
python language programming presentation
lbisht2
 
PDF
Python cheatsheet for beginners
Lahore Garrison University
 
PDF
Beginners python cheat sheet - Basic knowledge
O T
 
PDF
1. python
PRASHANT OJHA
 
PDF
Processing data with Python, using standard library modules you (probably) ne...
gjcross
 
PPTX
beginners_python_cheat_sheet_pcc_all (3).pptx
HongAnhNguyn285885
 
PDF
python.pdf
wekarep985
 
PPTX
Python.pptx
AshaS74
 
PDF
Introduction to python cheat sheet for all
shwetakushwaha45
 
PDF
Mementopython3 english
yassminkhaldi1
 
PDF
advanced python for those who have beginner level experience with python
barmansneha1204
 
Python Variable Types, List, Tuple, Dictionary
Soba Arjun
 
Introduction to Python
UC San Diego
 
Beginning Python
Agiliq Solutions
 
ComandosDePython_ComponentesBasicosImpl.ppt
oscarJulianPerdomoCh1
 
python cheat sheat, Data science, Machine learning
TURAGAVIJAYAAKASH
 
2. Python Cheat Sheet.pdf
MeghanaDBengalur
 
beginners_python_cheat_sheet_pcc_all (1).pdf
ElNew2
 
Beginner's Python Cheat Sheet
Verxus
 
python language programming presentation
lbisht2
 
Python cheatsheet for beginners
Lahore Garrison University
 
Beginners python cheat sheet - Basic knowledge
O T
 
1. python
PRASHANT OJHA
 
Processing data with Python, using standard library modules you (probably) ne...
gjcross
 
beginners_python_cheat_sheet_pcc_all (3).pptx
HongAnhNguyn285885
 
python.pdf
wekarep985
 
Python.pptx
AshaS74
 
Introduction to python cheat sheet for all
shwetakushwaha45
 
Mementopython3 english
yassminkhaldi1
 
advanced python for those who have beginner level experience with python
barmansneha1204
 
Ad

Recently uploaded (20)

DOCX
Cryptography Quiz: test your knowledge of this important security concept.
Rajni Bhardwaj Grover
 
DOCX
Python coding for beginners !! Start now!#
Rajni Bhardwaj Grover
 
PPTX
Manual Testing for Accessibility Enhancement
Julia Undeutsch
 
PDF
“Voice Interfaces on a Budget: Building Real-time Speech Recognition on Low-c...
Edge AI and Vision Alliance
 
PDF
Evolution: How True AI is Redefining Safety in Industry 4.0
vikaassingh4433
 
PDF
ICONIQ State of AI Report 2025 - The Builder's Playbook
Razin Mustafiz
 
PPTX
Talbott's brief History of Computers for CollabDays Hamburg 2025
Talbott Crowell
 
PDF
Kit-Works Team Study_20250627_한달만에만든사내서비스키링(양다윗).pdf
Wonjun Hwang
 
PPTX
Essential Content-centric Plugins for your Website
Laura Byrne
 
PPTX
Role_of_Artificial_Intelligence_in_Livestock_Extension_Services.pptx
DrRajdeepMadavi
 
PDF
Transforming Utility Networks: Large-scale Data Migrations with FME
Safe Software
 
PDF
Go Concurrency Real-World Patterns, Pitfalls, and Playground Battles.pdf
Emily Achieng
 
PDF
Dev Dives: Accelerating agentic automation with Autopilot for Everyone
UiPathCommunity
 
PDF
99 Bottles of Trust on the Wall — Operational Principles for Trust in Cyber C...
treyka
 
PPTX
The Project Compass - GDG on Campus MSIT
dscmsitkol
 
PDF
Transcript: Book industry state of the nation 2025 - Tech Forum 2025
BookNet Canada
 
PDF
NLJUG Speaker academy 2025 - first session
Bert Jan Schrijver
 
PDF
How do you fast track Agentic automation use cases discovery?
DianaGray10
 
PDF
“ONNX and Python to C++: State-of-the-art Graph Compilation,” a Presentation ...
Edge AI and Vision Alliance
 
PDF
Software Development Company Keene Systems, Inc (1).pdf
Custom Software Development Company | Keene Systems, Inc.
 
Cryptography Quiz: test your knowledge of this important security concept.
Rajni Bhardwaj Grover
 
Python coding for beginners !! Start now!#
Rajni Bhardwaj Grover
 
Manual Testing for Accessibility Enhancement
Julia Undeutsch
 
“Voice Interfaces on a Budget: Building Real-time Speech Recognition on Low-c...
Edge AI and Vision Alliance
 
Evolution: How True AI is Redefining Safety in Industry 4.0
vikaassingh4433
 
ICONIQ State of AI Report 2025 - The Builder's Playbook
Razin Mustafiz
 
Talbott's brief History of Computers for CollabDays Hamburg 2025
Talbott Crowell
 
Kit-Works Team Study_20250627_한달만에만든사내서비스키링(양다윗).pdf
Wonjun Hwang
 
Essential Content-centric Plugins for your Website
Laura Byrne
 
Role_of_Artificial_Intelligence_in_Livestock_Extension_Services.pptx
DrRajdeepMadavi
 
Transforming Utility Networks: Large-scale Data Migrations with FME
Safe Software
 
Go Concurrency Real-World Patterns, Pitfalls, and Playground Battles.pdf
Emily Achieng
 
Dev Dives: Accelerating agentic automation with Autopilot for Everyone
UiPathCommunity
 
99 Bottles of Trust on the Wall — Operational Principles for Trust in Cyber C...
treyka
 
The Project Compass - GDG on Campus MSIT
dscmsitkol
 
Transcript: Book industry state of the nation 2025 - Tech Forum 2025
BookNet Canada
 
NLJUG Speaker academy 2025 - first session
Bert Jan Schrijver
 
How do you fast track Agentic automation use cases discovery?
DianaGray10
 
“ONNX and Python to C++: State-of-the-art Graph Compilation,” a Presentation ...
Edge AI and Vision Alliance
 
Software Development Company Keene Systems, Inc (1).pdf
Custom Software Development Company | Keene Systems, Inc.
 

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\n&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...