1 / 337

Python Programming

Python Programming. by Chris Seddon. Python Programming. 13. Exception Handling 14. Unit Test 15. Inheritance 16. Threading 17. Extending and Embedding 18. Meta Classes 19. cx_Oracle 20. Operator Overloading 21. Web Application Frameworks 22. JSON and XML

cwen
Download Presentation

Python Programming

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Python Programming byChris Seddon

  2. Python Programming 13. Exception Handling 14. Unit Test 15. Inheritance 16. Threading 17. Extending and Embedding 18. Meta Classes 19. cx_Oracle 20. Operator Overloading 21. Web Application Frameworks 22. JSON and XML 23. Miscellaneous Topics • 1. Introduction to Python • 2. The Basics • 3. More on Data Types • 4. Functions • 5. Classes and Objects • 6. Modules and Packages • 7. Easy_Install and Pip • 8. Files • 9. Attribute Lookup • 10. Advanced Techniques • 11. Decorators • 12. Regular Expressions

  3. 1

  4. Introduction to Python IronPython

  5. What is Python? • Python is a Dynamic Scripting Language • not a static language like C++, C# and Java • easy to learn • no compile step • can be run a line at a time inside an interpreter (REPL) • Supports both Object Oriented and Functional styles • often described as an agile language • ideal for rapid prototyping and testing • often used as a plug-in to a C++ or Java system • extensive library • Python Virtual Machine • garbage collection • reference counted objects

  6. Advantages of Python • Python is often used ... • to develop small programs and scripts • simple programs can be created very quickly • ... but can be used for large-scale programming projects • sophisticated module and packaging scheme • extensive object oriented support • Python has a modern design • more natural coding style than Perl, Rexx and VBScript • highly portable

  7. What is Jython? • Jython is an implementation of Python • that compiles to Java byte code • runs on any JVM • highly portable • thread safe • Jython currently supports the Python syntax at level 2.5 • Jython Libraries • uses Java libraries because of the JVM • NOT standard Python libraries

  8. What is Iron Python? • .NET framework version of Python • runs in the CLR • only used on Windows systems (and mono) • Iron Python currently supports the Python syntax at level 2.7 • Iron Python Libraries • uses .NET libraries and Python libraries

  9. Everything is Interpreted • Python is an interpreted language • no compile step as in Java and C++ • each time Python code is run it is interpreted afresh into byte code • unless byte code cached internally • Code can also be entered interactively in the REPL myPython.py interpreter Target Hardware

  10. Performance • Python is interpreted • much slower than a compiled language such as C/C++ • increased design and coding flexibility more than makes up for performance loss • Python libraries usually written in C/C++ • a large proportion of the Python library is written in C/C++ • as is the interpreter itself • mitigates poor performance of pure Python • Python has modules to measure performance • profile, cProfile

  11. Invoking Python • 1. From the Command Line • code is entered one line at a time • see the results immediately • ideal way to learn Python • 2. Use Python Script files • interpreted by the Python runtime • source files can be combined using modules for larger applications • 3. PyDev plug-in for Eclipse • PyDev is very mature (10+ years development) • full debugging support

  12. Python Distributions • Python home page • http://www.python.org/ • Major Releases • Python 3.2.2 September 4, 2011 • Python 3.1.4 June 11, 2011 • Python 3.0.1 February 13, 2009 • Python 2.7.2 June 11, 2011 • Python 2.6.7 June 3, 2011 • Python 2.5.4 December 23, 2008 • Python 2.4.6 December 19, 2008 • Python 2.3.7 March 11, 2008 • Python 2.2.3 May 30, 2003 • Python 2.1.3 April 8, 2002 • Python 2.0.1 June 2001 • Python 1.6.1 September 2000

  13. Python Resources • Python docs • http://www.python.org/doc/ • http://docs.python.org/modindex.html • ActiveState Python • http://www.activestate.com/activepython/ • Python Tutorial by Guido van Rossum • http://www.python.org/doc/2.2.3/tut/tut.html • Python Cookbook • http://oreilly.com/catalog/9780596007973/

  14. Books • Python Essential Reference, Fourth Edition • By: David M. Beazley • Publisher: Addison-Wesley Professional • The Definitive Guide to Jython: Python for the Java™ Platform • By: Josh Juneau; Jim Baker; Victor Ng; Leo Soto; Frank Wierzbicki • Publisher: Apress • Expert Python Programming: Learn best practices to designing, coding, and distributing your Python software • By: Tarek Ziadé • Publisher: Packt Publishing

  15. 2

  16. The Basics

  17. A "Hello World" Example • Trivial one liner in Python • you don’t even require a semi-colon! print "Hello World!"

  18. Comments and Indentation • # for comments • Indentation instead of braces # this is a comment x = 100 y = 200 if x + y < 500: print "sum is less than 500" colon indent

  19. Input • Input is converted to a string • may need to use a cast x = int(raw_input("Please enter an integer: ")) x = x + 1 Please enter an integer: -5

  20. if Statements x = int(raw_input("Please enter an integer: ")) if x < 0: print 'Negative' Please enter an integer: -5 Negative

  21. if Statements x = int(raw_input("Please enter a positive integer: ")) if x > 0: print 'x is positive' print 'the square of x is', x * x print 'the cube of x is', x * x * x print 'End of if-statement' Please enter a positive integer: 66 x is positive the square of x is 4356 the cube of x is 287496 End of if-statement

  22. if-else Statements x = int(raw_input("Please enter an integer: ")) if x < 0: print 'Negative' else: print 'Not negative' Please enter an integer: 5 Not negative Please enter an integer: -5 Negative

  23. if-elif-else Statements x = int(raw_input("Please enter an integer: ")) if x < 0: print 'Negative' elif x == 0: print 'Zero' elif x == 1: print 'One' else: print 'Greater than one' Please enter an integer: -3 Negative Please enter an integer: 0 Zero Please enter an integer: 1 One Please enter an integer: 7 Greater than one

  24. Conditional if Statements x = 100 result = (-1 if x < 0 else 1) print result x = -200 result = (-1 if x < 0 else 1) print result 1 -1

  25. for Statements for x in (10,17,24,31,38,45,52,59,66,73,80,87,94): print x, print for x in range(10,100,7): print x, 10 17 24 31 38 45 52 59 66 73 80 87 94 10 17 24 31 38 45 52 59 66 73 80 87 94

  26. Using range • use range to iterate a fixed number of times for x in range(1,10): print x, 1 2 3 4 5 6 7 8 9

  27. for-else Statements for x in (1,2,3,4,5,6): print x, else: print "only get here if all iterations succeed ..." for x in (1,2,3,4,5,6): print x, if x > 3: break else: print "only get here if all iterations succeed ..." 1 2 3 4 5 6 only get here if all iterations succeed ... 1 2 3 4

  28. while Statements 1 4 2 12 3 24 4 40 5 60 6 84 7 112 8 144 9 180 10 220 11 264 12 312 13 364 14 420 15 480 16 544 17 612 18 684 19 760 20 840 21 924 22 1012 formula = 0 x = 0 while formula < 1000: x = x + 1 formula = 2*x*(x + 1) print x, formula

  29. Integers/Long • Unlimited precision • decimals, octal and hexadecimal x = 300 # decimal x = 053 # octal x = 0xFF # hex x = 1 for n in range(1,50000): x = x * n print x ... 86403721519060873367211627870277407019800467035376930071604547430881028943029710890094952575983102831942332098801078767873403184381230364583658736229882537596239041221481873021860189640178600542178564988974151405713305376974953837175072716957131738058858686051525163484354006340593710441714431751346890331014890001250991326209382486114202450838557226815940779632146588684231919129675780785628763938512135014594378778786201414551367351269240041448197911187026793326350625732189630574843722324400961845552066777053710654214427248892086625835653297347571207296418050723486268908764560304201574520900955804485505030632058537592545273742175612037061462858200453655527745928196559852331864722970592646723758606 ...

  30. Booleans • Values • True, False • Operators • and, or x = True y = False z = x or y print z z = x and y print z print type(z) True False <type 'bool'>

  31. Floating Point • 13 significant figures on 32 bit implementation • no exact representation # floating point x = 1e6 + 0.000001e-4 format = "%32.20g" print type(x) print (format % x) <type 'float'> 1000000.0000000001

  32. Complex Numbers • floating types • real and imaginary parts • can be extracted separately x = (+2.5-3.4j) - (-1.4+1.0j) print type(x) print x print x.real print x.imag <type 'complex'> (3.9-4.4j) 3.9 -4.4

  33. None • special type • NoneType x = 120 print type(x) print x x = None # not defined print type(x) print x if (x == None): x = 240 print x <type 'int'> 120 <type 'NoneType'> None 240

  34. 3

  35. Immutable Types int/long float tuple frozen set Mutable Types list dict set More On Data Types

  36. int float bool NoneType str str list tuple dict x = 200 x = 5.734 x = True x = None x = 'Hello' x = "Goodbye" x = [2,3,5,7,11,13,17] x = (2,3,5,7,11,13,17) x = { 'Tom':23000, 'Sue':24500, 'Zoe':21800} Object References • All data types are objects • x is an object reference (pointer) • can point to any type of object

  37. Immutable Types • Several types are immutable • int, float, str, NoneType, tuple • state cannot be modified after object is created • Immutable objects are often useful because they are inherently thread-safe • What happens when you try to change an immutable object? id(x) = unique id of object pointed at by x x = 100 print id(x) x = x + 1 print id(x) 10053412 10053400 x points to a different object

  38. Mutable Types • Several types are mutable • list, dict, class • Operations change state • id of object doesn't change x = [2,3,5,7,11,13,17] print id(x) x.append(23) print id(x) print x 43143336 43143336 [2, 3, 5, 7, 11, 13, 17, 23]

  39. Strings ... • immutable • single or double quotes • triple quoting for multi-line strings x = 'hello' y = "from" z = """the planet earth""" print type(x) print x, y, z phrase = x + " " + y + " " + z print phrase.upper() <type 'str'> hello from the planet earth HELLO FROM THE PLANET EARTH

  40. ... Strings • Many string manipulation methods available • original string is unchanged • new string returned s = "---abc:xyz:123---" t = s.lower() t = s.lstrip("-") t = s.replace(":","@") t = s.rstrip("-") t = s.split(":") t = s.strip("-") t = s.swapcase() t = s.upper() ---abc:xyz:123--- abc:XYZ:123--- ---abc@XYZ@123--- ---abc:XYZ:123 ['---abc', 'XYZ', '123---'] abc:XYZ:123 ---ABC:xyz:123--- ---ABC:XYZ:123---

  41. ... Strings • More string methods ... count(sub) number of occurrences of substring find(sub) index in the string where substring is found isalnum() true if string is alphanumeric isalpha() true if string is alphabetic isdigit() true if string is all digits join(seq) concatenate all the strings in the sequence partition(sep) split the string at the first occurrence of sep and return a 3-tuple split(sep) return a list of the words in the string using sep as the delimiter

  42. Tuple • immutable • can be nested • note syntax for a single item tuple x1 = () x2 = (1,) x3 = (1,2,3) x4 = (1, "mixed", 2, "tuple") x5 = ((1,2),(3,4)) print type(x1) print x1, "-----", len(x1) print x2, "-----", len(x2) print x3, "-----", len(x3) print x4, "-----", len(x4) print x5, "-----", len(x5) <type 'tuple'> ( ) ----- 0 (1,) ----- 1 (1, 2, 3) ----- 3 (1, 'mixed', 2, 'tuple') ----- 4 ((1, 2), (3, 4)) ----- 2

  43. List • mutable • can be nested x1 = [ ] x2 = [1] x3 = [1,2,3] x4 = [1, 'mixed', 2, 'list'] x5 = [[1,2],[3,4]] print type(x1) print x1, "-----", len(x1) print x2, "-----", len(x2) print x3, "-----", len(x3) print x4, "-----", len(x4) print x5, "-----", len(x5) <type 'list'> [ ] ----- 0 [1] ----- 1 [1, 2, 3] ----- 3 [1, 'mixed', 2, 'list'] ----- 4 [[1, 2], [3, 4]] ----- 2

  44. Memory Layout mylist = [ (10,20), [30,40] ]

  45. Modifying Lists • Lists can be extended • with another list • List can be appended • adds an element to a list list1 = [10, 20, 30] list2 = [55, 56, 57] list2.extend(list1) print list list2.append(99) print list2 [55, 56, 57, 10, 20, 30] [55, 56, 57, 10, 20, 30, 99]

More Related