introduction to python introduction to python
play

Introduction to Python Introduction to Python 1 Materials based on - PowerPoint PPT Presentation

Introduction to Python Introduction to Python 1 Materials based on contents from the course Programming with Python by Chad Haynes Outline Outline Overview Built-in objects Functions and scopes Object-oriented programming


  1. ������������ ������������ • Mapping - Associate a key with a value - Each key must be unique 'z' 'ab' 2.1 3 keys 10 [2] (3,8) 'hello' values 30

  2. ������������ ������������ • Construction - Syntax: {key1: value1, key2: value2 …} - Unordered map - Example: >>> dict1 = {'a': 1, 'b': 2} >>> dict1 {'a': 1, 'b': 2} >>> dict1['a'] 1 >>> dict1['b'] 2 31

  3. Control Flow Control Flow Examples if condition : if x%2 == 0: body y = y + x elif condition : else: body y = y - x else : body while condition : while i < 0: body count = count + 1 for name in iterable : for x in [1,2,3]: body sum = sum + x 32

  4. ������ ������������������� ������������������ ����� • Syntax: range([start,] stop[, step]) Generate a list of numbers from start to stop stepping every step - start defaults to 0, step defaults to 1 - - Example >>> range(5) [0, 1, 2, 3, 4] >>> range(1, 9) [1, 2, 3, 4, 5, 6, 7, 8] >>> range(2, 20, 5) [2, 7, 12, 17] 33

  5. ���������������� ���������������� • Using range with for Generate list used by for with range - - Example >>> for i in range(4): print i 0 1 2 3 34

  6. ���������������� ���������������� • The continue statement - Continue to next iteration of loop, skipping remainder of body - Example: >>> for x in range(8): if x%2 == 0: continue print x 1 3 5 7 35

  7. ���������������� ���������������� • The break statement - Break out of inner most loop - Example: >>> for number in range(10): if number == 4: print 'Breaking' break else: print number 0 1 2 3 36 Breaking

  8. �������������������� �������������������� • Data structures also have methods • Use built-in function dir to list all available methods • Example >>> lst = [1, 3, 2] >>> dir(lst) ['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__delslice__', '__doc__', '__eq__', '__ge__', '__getattribute__', '__getitem__', '__getslice__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__repr__', '__rmul__', '__setattr__', '__setitem__', '__setslice__', '__str__', 'append', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort'] 37

  9. ��������� � !��"��� !��"��� �������� • split - Syntax: string.split([sep]) - Returns a list of strings - Example: >>> text = "1 2 4 5 1" >>> text.split() ['1', '2', '4', '5', '1'] >>> test = "a, b, c, d, e" >>> test.split(',') ['a', ' b', ' c', ' d', ' e'] 38

  10. ��������� � !��"��� !��"��� �������� • strip - Syntax: string.strip() - Remove leading and trailing white space (tabs, new lines, etc) - Example: >>> padded = " stuff " >>> padded.strip() 'stuff' >>> padded ' stuff ' >>> unpadded = padded.strip() >>> unpadded 'stuff' 39

  11. ������� � !��"��� !��"��� ������ • append - Syntax: list.append(element) Add element to end of list - - Example: >>> list1 = [3, '10', 2] >>> list1.append('new') >>> list1 [3, '10', 2, 'new'] 40

  12. ������� � !��"��� !��"��� ������ • pop - Syntax: list.pop([index]) Remove and return item at position index from list - - Default is to remove last item - Example: >>> list1 = [3, '10', 2, 9, 11] >>> list1.pop() 11 >>> list1 [3, '10', 2, 9] 41

  13. ������� � !��"��� !��"��� ������ • insert - Syntax: list.insert(index, element) Insert element into list at position index - - Example: >>> list2 = [0, 1, 2, 3, 4, 5] >>> list2.insert(3, 'new') >>> list2 [0, 1, 2, 'new', 3, 4, 5] 42

  14. ������� � !��"��� !��"��� ������ • remove - Syntax: list.remove(element) Removes the first occurrence of element in list - - Example: >>> list2 = [0, 1, 3, 4, 3, 5] >>> list2.remove(3) >>> list2 [0, 1, 4, 3, 5] 43

  15. ������� � !��"��� !��"��� ������ • sort - Syntax: list.sort([cmpfunc]) Sort list in place - - Example: >>> list3 = [4, 12, 3, 9] >>> list3.sort() >>> list3 [3, 4, 9, 12] 44

  16. ������� � !��"��� !��"��� ������ • reverse - Syntax: list.reverse() Reverse elements of list in place - - Example: >>> list3 = [4, 12, 3, 9] >>> list3.reverse() >>> list3 [9, 3, 12, 4] 45

  17. �������������� � !��"��� !��"��� ������������� • keys - Syntax: dict.keys() Return a list of all the keys in dict - - Example: >>> dict1 = {1: 'a', 9: 'cat', 2: [2, 1]} >>> dict1.keys() [1, 2, 9] 46

  18. �������������� � !��"��� !��"��� ������������� • has_key - Syntax: dict.has_key(key) Determines if key is in dict - - Example: >>> dict1 = {'x': 1, 'y': 2} >>> dict1.has_key('x') 1 >>> dict1.has_key('w') 0 47

  19. �������������� � !��"��� !��"��� ������������� • values - Syntax: dict.values() Returns a list of all values in dict - - Example: >>> dict1 = {(1,2): 'a', (3,4): 'b', (9,8,7): 'c'} >>> dict1.values() ['a', 'c', 'b'] 48

  20. Getting Help Getting Help • For interactive use, calling help function will invoke the built-in help system • Call help() without argument for interactive mode >>> help(str) Help on class str in module __builtin__: class str(basestring) | str(object) -> string | | Return a nice string representation of the object. | If the argument is a string, the return value is the same object. | | Method resolution order: | str | basestring | object | | Methods defined here: | | __add__(...) | x.__add__(y) <==> x+y | | __contains__(...) | x.__contains__(y) <==> y in x : 49

  21. Functions and Scopes Functions and Scopes 50

  22. ��#��������������� ��#��������������� • Syntax: def func(arg1, …): body - Body of function must be indented If no value is returned explicitly, function will return None - - Example: >>> def average(num1, num2, num3): sum = num1 + num2 + num3 avg = sum / 3.0 return avg 51

  23. ��������� ��������� • Parameters - Parameters can be any type - A function can take any number of parameters (or none at all) - Example: >>> def usage(programName, version): print ‘%s Version %i' % (programName, version) print 'Usage: %s arg1 arg2‘ % (programName) >>> usage('Test', 1.0) Test Version 1.0 Usage: Test arg1 arg2 52

  24. ��������� ��������� • Default Parameters - One or more parameters can be given a default value - The function can be called with fewer arguments than there are parameters - All non-default (required) parameters must precede default parameters - Example: >>> def printName(last, first, mi=""): print "%s, %s %s" % (last, first, mi) >>> printName("Smith", "John") Smith, John >>> printName("Smith", "John", "Q") Smith, John Q 53

  25. ��������� ��������� • Calling functions - Syntax: func(arg1, arg2, … argn) - Order of arguments must match order of declared parameters - No type checking is done - Example >>> def display(arg1, arg2, arg3): print arg1 print arg2 print arg3 >>> display(1, 'x', 4.3) 1 x 54 4.3

  26. ��������� ��������� • Keyword arguments - Functions can be called using the keyword of the argument - Syntax: func(keyword=value, …) - The order of the values passed by keyword does not matter - Example def keywords(key1="X", key2="X", key3="X",key4="X"): print key1, key2, key3, key4 >>> keywords(key3="O", key2="O") X O O X >>> keywords() X X X X 55

  27. ��������� ��������� • Functions as variables - Functions can be assigned - Example def sub(a, b): return a-b >>> op = sub >>> print op(3, 5) -2 >>> type(op) <type 'function'> 56

  28. ��������� ��������� • Functions as parameters - Functions can be passed to other functions - Example def convert(data, convertFunc): for i in range(len(data)): data[i] = convertFunc(data[i]) return data >>> convert(['1', '5', '10', '53'], int) [1, 5, 10, 53] >>> convert(['1', '5', '10', '53'], float) [1.0, 5.0, 10.0, 53.0] >>> convert(['1', '5', '10', '53'], complex) 57 [(1+0j), (5+0j), (10+0j), (53+0j)]

  29. ��������� ��������� • Returning multiple values - Return a tuple containing the values to return - Example def separate(text, size=3): start = text[:size] end = text[-size:] return (start, end) >>> separate('sample text') ('sam', 'ext') >>> start, end = separate('sample text') >>> print start sam >>> print end 58 ext

  30. Generators Generators • Generators are functions that generate sequence of items – Generated sequence can be infinite def fibonacci(): i = j = 1 while True: r, i, j = i, j, i+j yield r for rabbits in fibbonacci(): print rabbits if rabbits > 100: break 1 1 2 3 5 8 13 21 34 55 89 144 59

  31. Namespaces and Scopes Namespaces and Scopes • Namespace – A mapping from names to objects – (Currently) implemented as Python dictionaries • Scope – A region of program where a namespace is directly accessible – Name references search at most 3 scopes: local , global , built-in – Assignments create or change local names by default – Can force arguments to be global with global command 60

  32. Scope Example Scope Example x = 99 def func(Y): Z = X+Y # X is not assigned, so it's global return Z func(1) 61

  33. !������ !������ • A file containing Python definitions and statements - Modules can be “imported” - Module file name must end in .py - Used to divide code between files math.py string.py import math import string … 62

  34. import ��������� ��������� import • Syntax 1: import <module name> - Module name is the file name without the .py extension - You must use the module name to call the functions - Example >>> import math >>> dir(math) ['__doc__', '__name__', 'acos', 'asin', 'atan', 'atan2', 'ceil', 'cos', 'cosh', 'e', 'exp', 'fabs', 'floor', 'fmod', 'frexp', 'hypot', 'ldexp', 'log', 'log10', 'modf', 'pi', 'pow', 'sin', 'sinh', 'sqrt', 'tan', 'tanh'] >>> print math.e 2.71828182846 >>> print math.sqrt(2.3) 1.51657508881 63

  35. import ��������� ��������� import • Syntax 2: from <module> import <name> - Import only a specific name from a module into global namespace - Module name is not required to access imported name - Example >>> from math import sqrt >>> sqrt(16) 4 >>> dir(math) Traceback (most recent call last): File "<stdin>", line 1, in <module> NameError: name 'math' is not defined 64

  36. import ��������� ��������� import • Syntax 2a: from <module> import * - Import everything from a module into global namespace - Example >>> dir() ['__builtins__', '__doc__', '__name__'] >>> from time import * >>> dir() ['__builtins__', '__doc__', '__name__', 'accept2dyear', 'altzone', 'asctime', 'clock', 'ctime', 'daylight', 'gmtime', 'localtime', 'mktime', 'sleep', 'strftime', 'struct_time', 'time', 'timezone', 'tzname'] >>> time() 1054004638.75 65

  37. Python Standard Libraries Python Standard Libraries • Some examples sys - System-specific parameters and functions time - Time access and conversions thread - Multiple threads of control re - Regular expression operations email - Email and MIME handling package httplib - HTTP protocol client Tkinter - GUI package based on Tcl/Tk • See http://docs.python.org/library/index.html 66

  38. ������$%���� ������$%���� • Opening a file - Syntax: open(fileName, mode) - Mode is one of: � 'r' : Read � 'w' : Write � 'a' : Append - If a file opened for writing does not exist it will be created - Example >>> inFile = open('input.txt', 'r') >>> type(infile) <type 'file'> 67

  39. ������$%������ � !��"��� !��"��� ������$%����� • read([size]) Read at most size bytes and return text as a string - • readlines([size]) - Read the lines of the file into a list of strings. Use size as an approximate bound on the number of bytes returned - 68

  40. ������$%������ � !��"��� !��"��� ������$%����� • write(text) Write text to the file - • writelines(string_sequence) - Write each string in the sequence to the file - New lines are not added to the end of the strings 69

  41. &��������� &��������� • Definition - Errors detected during execution • Basic Example - Divide by zero >>> 1 / 0 Traceback (most recent call last): File "<pyshell#0>", line 1, in ? 1 / 0 ZeroDivisionError: integer division or modulo by zero 70

  42. &��������� &��������� • Motivation - Move error handling code away from main code block - Deal with “exceptional” cases separately • How it works Exceptions are thrown (or raised) and caught - - Control exits the current code block when the exception is thrown - An exception can then be caught by a catching code block 71

  43. &��������� &��������� • Throwing - Many common operations may throw an exception � List index out of bounds � Invalid type conversions Exceptions can be thrown manually using the raise keyword - � >>> raise ValueError, "Bad Value“ • Catching - Thrown exceptions must be caught - If the exception is never caught the progam will terminate 72

  44. &��������� &��������� • Handling Syntax try: <try code block> except <Exception List>: <exception code block> except <Exception List>: <exception code block> except: <exception code block> else: <else code> 73

  45. &��������� &��������� • Example try: x = 1 / 0 except ZeroDivisionError: print 'Divide by zero error' Divide by zero error 74

  46. &��������� &��������� • Example try: x = 1 / 0 except IOError: print 'Input/Output error' except: print 'Unknown error' Unknown error 75

  47. &��������� &��������� • Types of Exceptions - There is a hierarchy of exceptions - All built-in exceptions are derived from Exception - An exception will be caught by any type higher up in the hierarchy Exception StandardError ArithmeticError ZeroDivisionError SystemExit ValueError OverflowError StopIteration LookupError IndexError KeyError 76

  48. &��������� &��������� • Example try: x = 1 / 0 except Exception: print 'Exception caught' Exception caught 77

  49. &��������� &��������� • Propagation If no proper except block can be found in the current block, the - exception propagates back to the calling function def func1(): try: a = 1 / 0 … except ValueError: print 'first' def func2(): try: func1() except: print 'second' >>> func2() second 78

  50. &��������� &��������� • Example try: x = 1 / 0 except Exception: print 'Exception caught' Exception caught 79

  51. OO Programming OO Programming 80

  52. Defining a Class Defining a Class • Syntax: class name [( base )]: body • Creating a class with no superclass class name : class name ( object ): body body Old-style class New-style class • Basically, classes are simply namespaces class MyClass(object): myvar = 30 >>> MyClass.myvar 30 81

  53. Class Example Class Example • All instance methods must explicitly take an instance as the first parameter – self is a commonly used name class Rectangle(object): def __init__(self, width, height): self.width = width self.height = height Constructor def area(self): return self.width * self.height >>> r = Rectangle(10, 20) >>> Rectangle.area(r) 200 >>> r.area() 200 82

  54. Inheritance Inheritance • Subclass must invoke parent's constructor explicitly class Square(Rectangle): def __init__(self, width): Rectangle.__init__(self, width, width) >>> s = Square(100) >>> s.area() 10000 83

  55. Polymorphism Polymorphism • All methods are virtual import math class Circle(object): def __init__(self, radius): self.radius = radius def area(self): return math.pi*self.radius*self.radius >>> shapes = [Square(5), Rectangle(2,8), Circle(3)] >>> for x in shapes: ... print x.area() ... 25 16 28.2743338823 84

  56. Python Object Hooks Python Object Hooks • Objects can support built-in operators by implementing certain special methods – The usual operators: + , - , * , / , ** , & , ^ , ~ , != – Indexing (like sequences): obj[idx] – Calling (like functions): obj(args,...) – Iteration and containment tests •for item in obj:... •if item in obj:... 85

  57. Functional Programming Functional Programming 86

  58. �����������'������"�� �����������'������"�� • Taken from functional languages - Lisp/Scheme - Haskell • Added to Python as built-in functions - map() - filter() - reduce() - zip() 87

  59. ������ ����#��������� ���#��������� map ����� map • Perform an operation on each element of a list - A function is applied to each element - The results of each function call are used to generate a new list - The resulting list is always the same length as the original list - The original list is not altered 88

  60. ������ ����#��������� ���#��������� map ����� map y 1 y 2 y 3 y 4 y 5 y 6 y 7 y 8 func ŷ 1 89

  61. ������ ����#��������� ���#��������� map ����� map y 1 y 2 y 3 y 4 y 5 y 6 y 7 y 8 func ŷ 1 ŷ 2 90

  62. ������ ����#��������� ���#��������� map ����� map y 1 y 2 y 3 y 4 y 5 y 6 y 7 y 8 func ŷ 1 ŷ 2 ŷ 3 91

  63. ������ ����#��������� ���#��������� map ����� map y 1 y 2 y 3 y 4 y 5 y 6 y 7 y 8 func ŷ 1 ŷ 2 ŷ 3 ŷ 4 92

  64. ������ ����#��������� ���#��������� map ����� map y 1 y 2 y 3 y 4 y 5 y 6 y 7 y 8 func ŷ 1 ŷ 2 ŷ 3 ŷ 4 ŷ 5 93

  65. ������ ����#��������� ���#��������� map ����� map y 1 y 2 y 3 y 4 y 5 y 6 y 7 y 8 func ŷ 1 ŷ 2 ŷ 3 ŷ 4 ŷ 5 ŷ 6 94

  66. ������ ����#��������� ���#��������� map ����� map y 1 y 2 y 3 y 4 y 5 y 6 y 7 y 8 func ŷ 1 ŷ 2 ŷ 3 ŷ 4 ŷ 5 ŷ 6 ŷ 7 95

  67. ������ ����#��������� ���#��������� map ����� map y 1 y 2 y 3 y 4 y 5 y 6 y 7 y 8 func ŷ 1 ŷ 2 ŷ 3 ŷ 4 ŷ 5 ŷ 6 ŷ 7 ŷ 8 96

  68. ������ ����#��������� ���#��������� map ����� map • Syntax 1: map(func, list) - Example: Convert a list of integers to strings >>> lst1 = [1, 2, 3, 4] >>> lst2 = map(str, lst1) >>> print lst2 ['1', '2', '3', '4'] - The function ( str ) takes one argument - The result ( lst2 ) is the same length as the original ( lst1 ) 97

  69. ������ ����#��������� ���#��������� map ����� map • What if the function requires more than one argument? - Multiple lists can be passed to the map function • Syntax 2: map(func, list 1 , …, list n ) - All lists must be of same length - The function must take n parameters 98

  70. ������ ����#��������� ���#��������� map ����� map • Example: adding numbers def add2(a, b): return a+b >>> lst1 = [0, 1, 2, 3] >>> lst2 = [4, 5, 6, 7] >>> print map(add2, lst1, lst2) [4, 6, 8, 10] 99

  71. ��������������� ��������������� lst1 = [1, 2, 3, 4] lst2 = [] for element in lst1: lst2.append(str(element)) lst1 = [1, 2, 3, 4] lst2 = map(str, lst1) 100

Recommend


More recommend