# -*- coding: utf-8 -*- # Gotchas! # whitespace, when copying code from a web page, or copy/paste from elsewhere, # or when you're changing things and forget, mid-change, what level was where. # find the bug: def is_prime(n): for divisor in range(2,math.sqrt(n)): if n % divisor == 0: return False return True # print and return are different! def plus_one_print(x): print x+1 def plus_one_return(x): return x+1 def plus_one_None(x): x + 1 # it's deceptive in the IDLE prompt: # >>> plus_one_print(3) # 4 # >>> plus_one_return(3) # 4 # >>> a = plus_one_print(3) # 4 # >>> a # >>> # >>> # NOTE: The value None prints as nothing at all, and functions without # >>> # an explicit return statement return None by default. # >>> a = plus_one_return(3) # >>> # Nothing has printed because assignment does not have a result # >>> a # 4 # >>> plus_one_None(3) # >>> # None, as before, because no return statement. # sometimes operations are defined that you wish wouldn't be: "3" < 5 def tru(x): if x: print x,"yes" else: print x,"no" tru(0) tru(1) tru(None) tru([]) tru({}) tru([0]) tru([False]) tru([None]) tru({"hi": None}) tru({None: "value"}) # integer division 7/3 + 5/3 # not 4 # precision 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 # ten of them 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 == 1 # ? class NdPoint: def __init__(self, coordinates): self.coordinates = coordinates def __str__(self): return "<"+ ",".join(map(str,self.coordinates)) + ">" # copy/paste: sometimes people copy a line and change it (almost) everywhere: cube = [NdPoint([0,0,0]), NdPoint([0,0,1]), NdPoint([0,1,0]), NdPoint([0,1,1]), NdPoint([0,0,0]), NdPoint([1,0,1]), NdPoint([1,1,0]), NdPoint([1,1,1])] # better to create it programmatically: cube2 = [] coordinates = [0,0,0] for x in [0,1]: for y in [0,1]: for z in [0,1]: coordinates[0] = x coordinates[1] = y coordinates[2] = z cube2.append(NdPoint(coordinates)) print "cube2:", [str(x) for x in cube2] # barebones aliasing: a = [1,2,3] def foo(x): x[0] *= 2 return x b = foo(a) # it's hard to see without examining foo that b[1] = 19 # changing b will now affect a a # is [2, 19, 3] # tuples: t = (3,4) # like lists but immutable: cannot say t[0]=1 t + 5 # Error. ok. t + (5) # Error: these parens are arithmetic grouping t + (5,) # is what you wanted (t, (5,)) # is nested (t, (5,)) + ((6,7)) # --> ((3, 4), (5,), 6, 7) (t, (5,)) + ((6,7),) # --> ((3, 4), (5,), (6, 7)) print 3,4 # prints "3 4\n" print(3,4) # prints "(3, 4)\n" because that's a tuple on a statement, not a fn # So: four kinds of executables: functions, methods, operators, statements # three contexts for parentheses: arithmetic, function-call, tuple # People often confuse them! # broken closures, if you care about that kind of thing.