1
Introduction to Python Introduction to Python
Materials based on contents from the course Programming with Python by Chad Haynes
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
Materials based on contents from the course Programming with Python by Chad Haynes
2
3
import math def showArea(shape): print "Area = %d" % shape.area() def widthOfSquare(area): return math.sqrt(area) class Rectangle(object): def __init__(self, width, height): self.width = width self.height = height def area(self): return self.width * self.height ###### Main Program ###### r = Rectangle(10, 20) showArea(r)
Function definition Class definition Import a library module Calling a function Comment Object instantiation
4
5
6
7
if (x < 10) { x = x + tmp; y = y * x; } System.out.println(y);
Java
if x < 10: x = x + tmp y = y * x print y
Python
8
9
using System; class Hello { static void Main() { Console.WriteLine("Hello, World"); } }
print "Hello, World!"
10
>>> x = 23 >>> print x 23 >>> x = 'foo' >>> print x foo >>> del x >>> print x Traceback (most recent call last): File "<stdin>", line 1, in <module> NameError: name 'x' is not defined >>> name x means 23 now it means 'foo' x becomes undefined
11
Var1 Var1_copy Var2
12
13
– 'Single Quotes' – "Double Quotes" – """Triple Quotes"""
14
>>> info = raw_input('-> ')
>>> print info Here is info
15
* // / ** % abs
>>> 5 + 3 # Addition 8 >>> 2 ** 8 # Exponentiation 256 >>> 13 / 4 # Integer (Truncating) Division* 3 >>> float(13) / 4 # Float Division 3.25 >>> 13 % 4 # Remainder 1 >>> abs(-3.5) # Absolute Value 3.5
16
>>> 4 > 1.5 1 >>> 'this' != 'that' 1 >>> 4+3j == 4-2j >>> '5' == 5 >>> 0 < 10 < 20 1
17
i2 i1 and i2 1 1 1 1 1 i1 or i2 1 1 1 i1 not i1 1 1
18
>>> 1 == 1 and 2 >= 3 >>> 1 == 1 or 2 >= 3 1 >>> not 5.3 != 2.2 # same as: not (5.3 != 2.2) >>> 2 and '23' > '11' or 0 1
19
>>> 'Rockefeller' + 'University' 'RockefellerUniversity'
>>> 'dog' * 5 'dogdogdogdogdog'
20
>>> "%i %s in the basket" % (2, "eggs") '2 eggs in the basket' >>> "%f to 2 decimal places: %.2f" %(2.0/9.0, 2.0/9.0) '0.222222 to 2 decimal places: 0.22' >>> length = 5 >>> obj = "fence" >>> "Length of the %(obj)s is %(length)i" % vars() 'Length of the fence is 5'
21
>>> type(2.45) <type 'float'> >>> type('x') <type 'str'> >>> type(2**34) <type 'long'> >>> type(3+2j) <type 'complex'>
22
>>> str(42.3) '42.3' >>> float('-1.32e-3')
>>> int('0243') 243 >>> int(2**34) Traceback (most recent call last): File "<pyshell#12>", line 1, in ? int(2**34) OverflowError: long int too large to convert to int >>> long(2**34) 17179869184L
23
24
>>> list1 = [1, 'hello', 4+2j, 123.12] >>> list1 [1, 'hello', (4+2j), 123.12] >>> list1[0] = 'a' >>> list1 ['a', 'hello', (4+2j), 123.12]
25
>>> [1, 'a', 'b'] + [3, 4, 5] [1, 'a', 'b', 3, 4, 5]
>>> [23, 'x'] * 4 [23, 'x', 23, 'x', 23, 'x', 23, 'x']
26
2 3 4 5 6
a b c d e f g sequence[0] == a sequence[-7] == a sequence[6] == g sequence[-1] == g sequence[2] == c sequence[-5] == c
27
>>> sequence = [0, 1, 2, 3, 4, 5, 6, 7] >>> sequence[1:4] [1, 2, 3] >>> sequence[2:-1] [2, 3, 4, 5, 6]
>>> sequence[:2] [0, 1] >>> sequence[3:] [3, 4, 5, 6, 7]
28
>>> tuple1 = (1, 5, 10) >>> tuple1[2] = 2 Traceback (most recent call last): File "<pyshell#136>", line 1, in ? tuple1[2] = 2 TypeError: object doesn't support item assignment
29
>>> list1 = [1, 2, 3, 4, 5] >>> len(list1) 5 >>> string1 = "length of a string" >>> len(string1) 18
30
'ab' 2.1 3 keys 10 [2] (3,8) 'hello' values
31
>>> dict1 = {'a': 1, 'b': 2} >>> dict1 {'a': 1, 'b': 2} >>> dict1['a'] 1 >>> dict1['b'] 2
32
if condition: body elif condition: body else: body
Examples
if x%2 == 0: y = y + x else: y = y - x while i < 0: count = count + 1 for x in [1,2,3]: sum = sum + x while condition: body for name in iterable: body
33
>>> 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]
34
>>> for i in range(4): print i 1 2 3
35
>>> for x in range(8): if x%2 == 0: continue print x
3 5 7
36
>>> for number in range(10): if number == 4: print 'Breaking' break else: print number 1 2 3 Breaking
37
>>> 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']
38
>>> 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']
39
>>> padded = " stuff " >>> padded.strip() 'stuff' >>> padded ' stuff ' >>> unpadded = padded.strip() >>> unpadded 'stuff'
40
>>> list1 = [3, '10', 2] >>> list1.append('new') >>> list1 [3, '10', 2, 'new']
41
>>> list1 = [3, '10', 2, 9, 11] >>> list1.pop() 11 >>> list1 [3, '10', 2, 9]
42
>>> list2 = [0, 1, 2, 3, 4, 5] >>> list2.insert(3, 'new') >>> list2 [0, 1, 2, 'new', 3, 4, 5]
43
>>> list2 = [0, 1, 3, 4, 3, 5] >>> list2.remove(3) >>> list2 [0, 1, 4, 3, 5]
44
>>> list3 = [4, 12, 3, 9] >>> list3.sort() >>> list3 [3, 4, 9, 12]
45
>>> list3 = [4, 12, 3, 9] >>> list3.reverse() >>> list3 [9, 3, 12, 4]
46
>>> dict1 = {1: 'a', 9: 'cat', 2: [2, 1]} >>> dict1.keys() [1, 2, 9]
47
>>> dict1 = {'x': 1, 'y': 2} >>> dict1.has_key('x') 1 >>> dict1.has_key('w')
48
>>> dict1 = {(1,2): 'a', (3,4): 'b', (9,8,7): 'c'} >>> dict1.values() ['a', 'c', 'b']
49
>>> 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 :
50
51
>>> def average(num1, num2, num3): sum = num1 + num2 + num3 avg = sum / 3.0 return avg
52
>>> 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
53
parameters
>>> def printName(last, first, mi=""): print "%s, %s %s" % (last, first, mi) >>> printName("Smith", "John") Smith, John >>> printName("Smith", "John", "Q") Smith, John Q
54
>>> def display(arg1, arg2, arg3): print arg1 print arg2 print arg3 >>> display(1, 'x', 4.3) 1 x 4.3
55
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
56
def sub(a, b): return a-b >>> op = sub >>> print op(3, 5)
>>> type(op) <type 'function'>
57
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) [(1+0j), (5+0j), (10+0j), (53+0j)]
58
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 ext
59
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
60
61
x = 99 def func(Y): Z = X+Y # X is not assigned, so it's global return Z func(1)
62
import math import string … math.py string.py
63
>>> 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
64
>>> 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
65
>>> 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
66
67
>>> inFile = open('input.txt', 'r') >>> type(infile) <type 'file'>
68
69
70
>>> 1 / 0 Traceback (most recent call last): File "<pyshell#0>", line 1, in ? 1 / 0 ZeroDivisionError: integer division or modulo by zero
71
72
73
try: <try code block> except <Exception List>: <exception code block> except <Exception List>: <exception code block> except: <exception code block> else: <else code>
74
try: x = 1 / 0 except ZeroDivisionError: print 'Divide by zero error' Divide by zero error
75
try: x = 1 / 0 except IOError: print 'Input/Output error' except: print 'Unknown error' Unknown error
76
Exception StandardError StopIteration SystemExit ArithmeticError LookupError ValueError IndexError KeyError OverflowError ZeroDivisionError
77
try: x = 1 / 0 except Exception: print 'Exception caught' Exception caught
78
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
79
try: x = 1 / 0 except Exception: print 'Exception caught' Exception caught
80
81
class MyClass(object): myvar = 30 >>> MyClass.myvar 30
class name[(base)]: body class name: body
Old-style class New-style class
class name(object): body
82
class Rectangle(object): def __init__(self, width, height): self.width = width self.height = height def area(self): return self.width * self.height >>> r = Rectangle(10, 20) >>> Rectangle.area(r) 200 >>> r.area() 200
Constructor
83
class Square(Rectangle): def __init__(self, width): Rectangle.__init__(self, width, width) >>> s = Square(100) >>> s.area() 10000
84
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
85
86
87
88
89
func y1 y2 y3 y4 y5 y6 y7 y8 ŷ1
90
func y1 y2 y3 y4 y5 y6 y7 y8 ŷ2 ŷ1
91
func y1 y2 y3 y4 y5 y6 y7 y8 ŷ3 ŷ1 ŷ2
92
func y1 y2 y3 y4 y5 y6 y7 y8 ŷ4 ŷ1 ŷ2 ŷ3
93
func y1 y2 y3 y4 y5 y6 y7 y8 ŷ5 ŷ1 ŷ2 ŷ3 ŷ4
94
func y1 y2 y3 y4 y5 y6 y7 y8 ŷ6 ŷ1 ŷ2 ŷ3 ŷ4 ŷ5
95
func y1 y2 y3 y4 y5 y6 y7 y8 ŷ7 ŷ1 ŷ2 ŷ3 ŷ4 ŷ5 ŷ6
96
func y1 y2 y3 y4 y5 y6 y7 y8 ŷ8 ŷ1 ŷ2 ŷ3 ŷ4 ŷ5 ŷ6 ŷ7
97
>>> lst1 = [1, 2, 3, 4] >>> lst2 = map(str, lst1) >>> print lst2 ['1', '2', '3', '4']
98
99
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]
100
lst2 = [] for element in lst1: lst2.append(str(element)) lst1 = [1, 2, 3, 4] lst2 = map(str, lst1)
101
lst2 = [4, 5, 6, 7] lst3 = [] for index in range(len(lst1)): lst3.append(add2(lst1[index], lst2[index])) lst1 = [0, 1, 2, 3] lst2 = [4, 5, 6, 7] lst2 = map(add2, lst1, lst2)
102
>>> lst1 = [1, 2, 3, 4] >>> string.join(lst1) # Error because lst1 contains ints … TypeError: sequence item 0: expected string, int found >>> string.join( map(str, lst1) ) # Correct '1 2 3 4'
103
104
def removeNegative(number): return number >= 0 >>> lst1 = [1, 2, -3, 4] >>> lst2 = filter(removeNegative, lst1) >>> print lst2 [1, 2, 4]
105
lst2 = [] for element in lst1: if removeNegative(element): lst2.append(element) lst1 = [1, 2, -3, 4] lst2 = filter(removeNegative, lst1)
106
107
func y1 y2 y3 y4 t1 func t2 func t3
108
1+10 1 10 20 30 11 11+20 31 31+30 61
109
>>> lst1 = [1, 2, 3, 4] >>> sum = reduce(operator.add, lst1) >>> print sum 10
110
>>> lst1 = [ [2, 4], [5, 9], [1, 7] ] >>> result = reduce(operator.add, lst1, [100]) >>> print result [100, 2, 4, 5, 9, 1, 7]
111
sum = operator.add(lst1[0], lst1[1]) for element in lst1[2:]: sum = operator.add(sum, element) lst1 = [1, 2, 3, 4] sum = reduce(operator.add, lst1)
112
result = operator.add([100], lst1[0]) for element in lst1[1:]: result = operator.add(sum, element) lst1 = [ [2, 4], [5, 9], [1, 7] ] result = reduce(operator.add, lst1, [100])
113
114
y1 y2 y3 y4 x1 x2 x3 x4 (x1, y1) (x2, y2) (x4, y4) (x3, y3)
115
>>> lst1 = [1, 2, 3, 4] >>> lst2 = ['a', 'b', 'c', 'd', 'e'] >>> result = zip(lst1, lst2) >>> print result [(1, 'a'), (2, 'b'), (3, 'c'), (4, 'd')]
116
lst2 = ['a', 'b', 'c', 'd', 'e'] lst3 = [] for index in range(min(len(lst1), len(lst2)): lst3.append( (lst1[index], lst2[index]) ) lst1 = [1, 2, 3, 4] lst2 = ['a', 'b', 'c', 'd', 'e'] lst3 = zip(lst1, lst2)
117
>>> produce = ['apples', 'oranges', 'pears'] >>> prices = [0.50, 0.45, 0.55] >>> for fruit, cost in zip(produce, prices): print '%s cost $%.2f'%(fruit, cost) apples cost $0.50
pears cost $0.55
118
>>> produce = ['apples', 'oranges', 'pears'] >>> prices = [0.50, 0.45, 0.55] >>> priceDict = dict(zip(produce, prices)) >>> print priceDict {'pears': 0.55, 'apples': 0.5, 'oranges': 0.45}
119
120
>>> [x+1 for x in range(5)] [1, 2, 3, 4, 5]
>>> [str(x) for x in range(5)] ['0', '1', '2', '3', '4']
121
>>> lst1 = [5, 10, 3, 9] >>> [x for x in lst1 if x != min(lst1)] [5, 10, 9]
>>> lst1 = [[1, 2, 4], [3, 1], [5, 9, 10, 11]] >>> [reduce(operator.add, x) for x in lst1 if len(x) > 2] [7, 35]
122
>>> nucleo = ['a', 'g', 'c', 't'] >>> [a+b for a in nucleo for b in nucleo] ['aa', 'ag', 'ac', 'at', 'ga', 'gg', 'gc', 'gt', 'ca', 'cg', 'cc', 'ct', 'ta', 'tg', 'tc', 'tt']
123
results = [] for a in nucleo: for b in nucleo: results.append(a+b) nucleo = ['a', 'g', 'c', 't'] results = [a+b for a in nucleo for b in nucleo]
124
125
>>> add2 = lambda a,b: a+b >>> print add2(1, 5) 6
>>> fac = lambda x: reduce(lambda a,b: a*b, range(1, x+1)) >>> print fac(5) 120
126
127
$ python freq.py http://www.cpe.ku.ac.th/~cpj/gpl.txt 345: the 221: of 192: to 184: a 151: or 128: you 102: license 98: and 97: work 91: that $
128
import urllib contents = urllib.urlopen(url).read() import sys url = sys.argv[1] import re words = re.findall('[A-Za-z]+', text)