1 / 200

Python Fundamentals

Python Fundamentals. by Chris Seddon. Python Fundamentals. 1 . Introduction to Python 2. Control Structures 3. Basic Data Types 4. Advanced Data Types 5. Dictionaries 6. Functions 7. Exception Handling 8. Classes and Objects 9. Files 10. Larger Programs 11. Inheritance

ethelyng
Télécharger la présentation

Python Fundamentals

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 Fundamentals byChris Seddon

  2. Python Fundamentals 1. Introduction to Python 2. Control Structures 3. Basic Data Types 4. Advanced Data Types 5. Dictionaries 6. Functions 7. Exception Handling 8. Classes and Objects 9. Files 10. Larger Programs 11. Inheritance 12. Further Topics 13. Pattern Matching 14. Unit Test

  3. Chapter 1 1

  4. Introduction to Python IronPython

  5. What is Python? Python is a scripting language unlike C++, C# and Java easy to learn no compile step can be run a line at a time inside an interpreter supports dynamic execution of source (you can type in code at run time) Supports both Object Oriented and functional styles of programming often described as an agile language capable of performing a wide variety of tasks ideal for rapid prototyping often used as a plug-in to a C++ or Java system

  6. Advantages of Python Python is best used to develop small programs and scripts simple programs can be created very quickly Python can be used for large-scale programming projects sophisticated module and packaging scheme extensive object oriented support Jython has access to all Java libraries Python was designed to be an object oriented language from the start more simplified and natural coding style than Perl, Rexx and VBScript highly portable

  7. What is Jython? An implementation of Python fully integrated with the Java Virtual Machine runs on any JVM unlike a Python program including Windows, Mac OS, most UNIX, all Linux systems, and all IBM systems highly portable because of the connection with Java Jython currently supports the Python syntax at level 2.5 Jython Libraries uses Java libraries because of the JVM NOT standard Python libraries can be a problem sometimes

  8. Everything is Interpreted Python is an interpreted language no pre-compile step as in Java and C++ each time Python code is run it is interpreted afresh code changes can be very quickly made and tested code can also be entered interactively can dynamically construct Python code, in the form of a string and execute it directly myPython.py myJava.java myJava.class Target Hardware JVM

  9. 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 hence high performance Python has modules to measure performance profile, cProfile

  10. Invoking Python Use the Command-Line Interpreter code is entered one line at a time see the results immediately ideal way to learn Python Use Python source files complied by the Python interpreter source files can be combined using modules for larger applications Python plug-in for Eclipse is often a good choice PyDev is very mature

  11. A "Hello World" Example The Hello World example is a trivial one liner in Python; you don’t even require a semi-colon! print "Hello World!"

  12. Further Example The Hello World example is a trivial one liner in Python; you don’t even require a semi-colon! # this is a comment x = 100 y = 200 if x + y < 500: print "sum is less than 500" colon indent

  13. Chapter 2 2

  14. Control Structures Statements if for while

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

  16. 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

  17. 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

  18. 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

  19. 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

  20. 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

  21. 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

  22. 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

  23. 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

  24. Chapter 3 3

  25. Basic Data Types Basic Types int long boolean float complex string

  26. Data Types Everything is an object including all types discussed in this chapter full documentation for the Java types is online Several types are immutable strings, tuples Sometimes objects behave as though immutable if you attempt to modify a number, Python simply creates a new object and marks the old object ready for garbage collection could lead to excessive delays during the garbage collection cycle.

  27. Built in Types int C long includes Booleans hex and octal numbers available boolean True, False, and, or float C double type (13 sig. fig.) long unlimited precision e.g. 10000000000000000000000000 complex real and imaginary parts are each implemented using Java double e.g. (5.0+3.1j)

  28. Integers Limited precision decimals, octal and hexadecimal # integers x = 100 x += 1 print type(x) print x x = 053 print x x = 0xFF print x <type 'int'> 101 43 255

  29. 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'>

  30. Floating Point 13 significant figures on 64 bit implementation no exact representation # floating point x = 1e4 + 0.1e-4 format = "%32.20g" print type(x) print (format % x) <type 'float'> 10000.000009999999747

  31. 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

  32. Integers are Immutable x is really an object reference (pointer) id(x) refers to the object at the end of the pointer x can change, but integer it points to is immutable x just points to a different object the original object gets garbage collected x = 100 print id(x) x = x + 1 print id(x) 10053412 10053400

  33. 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

  34. ... 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---

  35. ... 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

  36. Chapter 4 4

  37. Advanced Data Types Sequence Types list (mutable) use [ ] tuple (immutable) use ( ) set no duplicates Dictionary Types dict (mutable) use { }

  38. 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

  39. ... List Lists can be extended with extend or append Elements can be modified object reference gets changed Can contain immutable items such as tuples list1 = [[1,2],[3,4]] # notation for accessing lists print list1 print list1[1] print list1[1][0] # modifying lists list1[1][0] = 99 print list1[1][0] # append and extend are equivalent list2 = [10, 20, 30] list = [ ] list.extend(list1) list.append(list2) print list # lists can contain tuples list3 = [(1,2), (3,4), (5,6)] print list3

  40. 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

  41. Accessing Lists and Tuples only lists can be modified tuples are immutable mylist = [10, 20, 30] mytuple = (10, 20, 30) y = mytuple[0] y = mytuple[1] y = mytuple[2] x = mylist[0] x = mylist[1] x = mylist[2] mylist[1] = 99 mylist.append(40) print mylist [10, 99, 30, 40]

  42. Casting between Lists and Tuples use a cast to convert tuple( ... ) list( ...) theList = [2, 3, 5, 7, 11, 13, 17] myTuple = tuple(theList) myList = list(myTuple) print myTuple print myList (2, 3, 5, 7, 11, 13, 17) [2, 3, 5, 7, 11, 13, 17]

  43. Slices Sequences support slicing selects a range of elements (-1 represents the last element) x[1:3] selects the second through third elements of x the end index is always one past the selection assignment slicing replaces multiple elements x[3:5] = (5,4) colors = ["red", "blue", "green", "white", "black"] print colors[1] print colors[1:3] print colors[1:] print colors[-3:-1] print colors[4:1:-1] colors[2:4] = ("purple", "cyan") print colors[0:]; blue ['blue', 'green'] ['blue', 'green', 'white', 'black'] ['green', 'white'] ['black', 'white', 'green'] ['red', 'blue', 'purple', 'cyan', 'black']

More Related