# control statements in Python # for some students, Python's block structure # (using indentation instead of { .. } to define a block) # is the most difficult part of learning Python def f(): print "one" print "two" # notice that the body of function f is indented # recommendation: do not use tabs to indent # wrong example: def g(): print "one" print "two" # don't make irregular indentation: line statements up, please # the if/else statement def h(t): ' t is supposed to be tuple and h(t) returns True if t[0]>t[1]' if type(t) != type((1,)): # test for tuple return False if len(t) != 2: return False (a,b) = t if a>b: return True else: return False # notice (1) that "if" doesn't need (...) around condition, # (2) that "if" statement needs ":" after the condition # (3) new block of statements needs more indentation # (4) for a one-liner, can put on same line as "if" # other forms of "if" def k(a,b,c): if a>b: if c>a: d =b-a else: d = b elif a==b: d = b**2 # Python uses ** for exponentiation (instead of ^) else: d = b+a if d>1000: return -1 return d # recommendation: don't use complicated if/elif/else logic # (it makes code harder to read, and small indentation errors # could be hard to find unless you have some debugging tool) # the "for" statement def sum(sX): sum = 0 for e in sX: sum += e return e # using range(...) def sum2(sY): sum = 0 for i in range(0,len(sY)): sum = sum + sY[i] return sum # using while(...) def sum3(sY): sum = 0 while len(sY)>0: sum += sY[0] sY = sY[1:] return sum # another way to do the same thing (because + is commutative) def sum4(sY): sum = 0 while len(sY)>0: sum += sY[-1] # add last element of sY sY = sY[:-1] return sum # note: be careful modifying a list and using "while" as above, # because Python's implementation may test the "while" condition # in a different way than what you expect, for example: def elimNeg(a): i = 0 while i>> elimNeg([2,2,2,-3,-3,-3]) [2, 2, 2, -3] # same can happen with "for" statements, for instance def elimPos(a): for x in a: if x > 0: a.remove(x) return a >>> elimPos([2,2,2,-3,-3,-3]) [2, -3, -3, -3] # other control statements: # continue, break, pass, try (to catch exceptions), raise, yield # you can read about these as needed # missing from Python: "switch", "select", "goto" # Python has other exotic ways of looping: # lambdas, list comprehensions # -- probably not useful in this course (of course, you can use # recursion if you like)