python foo.py
>>> a = "3 5 8" >>> a.split() ['3', '5', '8']split is a nice way to break input lines into fields.
>>> a = "brad vander zanden, yifan tang, george brett" >>> names = a.split(',') >>> names ['brad vander zanden', ' yifan tang', ' george brett'] >>> names[1].strip() 'yifan tang'
>>> x = 1 >>> s = 'the value of x is ' + x TypeError: cannot concatenate 'str' and 'int' objects >>> s = 'the value of x is ' + str(x) >>> s 'the value of x is 1'
a = [3, 4, 5] b = a b[2] = 8 a // prints [3, 4, 8]
a, b = 0, 1 while b < 10: print (b) a, b = b, a+bComments
10 <= a <= 20 # true if a between 10 and 20 a < b == c # true if a < b and b == c
if name in ['frank', 'george', 'ralph']:is equivalent to
if (name == 'frank') or (name == 'george') or (name == 'ralph'):
if condition: statements elif condition: statements elif condition: statements ... else: statements
for var in sequence: statements that operate on varFor example, the following code sums the elements of a list:
sum = 0 for value in data: sum = sum + value
range(4) # yields [0, 1, 2, 3]
range(0, 10, 3) # yields [0, 3, 6, 9] range(10, 0, -3) # yields [10, 7, 4, 1]
sum = 0 for i in range(1,11): sum = sum + i
>>> for i, v in enumerate(['tic', 'tac', 'toe']): ... print (i, v) ... 0 tic 1 tac 2 toe
>>> vector1 = [10, 20, 30, 40, 50] >>> vector2 = [5, 10, 15, 20, 25] >>> for v1, v2 in zip(vector1, vector2): ... product = product + v1 * v2 ... >>> product 2750
for v1 in reversed(vector1): print (v1)
>>> people = { 'brad': 45, 'yifan': 36, 'smiley' : 5 } >>> for k, v in people.iteritems(): ... print (k, v) ... yifan 36 smiley 5 brad 45
for n in range(2, 10): for x in range(2, n): if n % x == 0: print (n, 'equals', x, '*', n/x) break else: # loop fell through without finding a factor print (n, 'is a prime number')
def functionName(args): """ Documentation String """ (optional) function body return value
def foo(): global x ... statements that modify x ...
def dfs(x, y): """ Perform a depth first search starting at x and ending at y Parameters x: The node from which to start the search y: The node at which to terminate the search Side-Effects: None """ ...
def makeFormula(formula): return lambda: formula newFormula = makeFormula("a + b")Here's another example that creates an incrementer:
def makeIncrementer(n): return lambda x: x + n f = make_incrementor(42) f(1) # returns 43
lambda x,y: x if x < y else y
>>> def fib(): ... yield 1 ... yield 1 ... current, prev = 1, 1 ... while True: ... current, prev = current + prev, current ... yield current ... >>> for i in fib(): ... if i > 100: ... break ... print (i) ... 1 1 2 3 5 8 13 21 34 55 89
>>> a = fib() >>> next(a) 1 >>> next(a) 1 >>> next(a) 2 >>> next(a) 3 >>> next(a) 5
def factorial(n): if n == 1: yield 1 else yield n * fact(n-1)This won't work like you think because you expect fact(n-1) to return a number, but it in fact returns a generator object and hence the multiplication fails with a type error.
There are sophisticated solutions beyond the scope of this course for doing recursive generator functions. An easier way is to declare a nested function that returns a list of the results, and then returns the results one at a time:
def factorial(n): def fact(n): if n == 1: return [1] else: result = fact(n-1) result.append(n*result[-1]) return result results = fact(n) for i in results: yield i