# Audience: # - has programmed # - perhaps in python # Agenda: # # - working in python with idle or emacs # - version / download # - repl vs. file # - syntax errors # - errors with backtraces # # - accomplishing things # - basic data types # - names # - functions and scope # - assert # - recursion # - break vs. return vs. exception # - classes # - lists # - indexing # - copying # - dictionaries # - list comprehensions (map&filter) # # - common gotchas # - whitespace # - print vs. return # - magical helpfulness # - integer division # - floating point precision # - copy/paste # - aliasing # - tuples and parentheses 3 3 + 2 # have numbers 13 - 2 * 4 # they do what you expect (13 - 2) * 4 # you can use parentheses to indicate precedence, as usual 8 / 2 # division is exact, like in C 8 / 2.0 # unless you specify otherwise 7 % 3 # modulo, etc. 3.0 == 3 # equality is not stupid "hi" # have strings "pin" + "to" # can add them to concatenate 3 * "pin" # can multiply them to repeat 'pin' * 3 # single quotes okay. 3 < 5 # have booleans 5 < 3 type(3) == int # types are first class objects # Names and Scope a = 3 a = 5 b = a a = 10 b #? # multiple assignment (a, b) = [1, 2] a b # Functions: my favorite datatype def plus_one(a): return a + 1 # whitespace sensitive def plus(a, b): return a + b def plus_ten(a): b = a + 10 return b a = 5 b = 3 c = 7 d = plus_ten(c) a #? b #? c #? d #? # if x = 1 # interactive model: syntax errors # interactive model: variable completion def near(a, b, tolerance=0.1): return abs(a - b) < tolerance def is_even(n): return n % 2 == 0 def assert_equal(expected, observed, message=""): assert expected == observed, ("Expected [%s] but found [%s]: %s" % (expected, observed, message)) print "ok." # recursion def integer_times(a, b): # todo: check that it's an integer if b == 0: # base case: return 0 else: # recursive step: return a + integer_times(a, b-1) ''' #RESET elif b < 0: return integer_times(-a, -b) ''' def test_integer_times(): assert_equal(1, integer_times(1,1)) assert_equal(0, integer_times(1,0)) assert_equal(0, integer_times(0,1)) assert_equal(6, integer_times(2,3)) assert_equal(-6, integer_times(-2,3)) assert_equal(-6, integer_times(2,-3)) assert_equal(6, integer_times(-2,-3)) test_integer_times() # RESET def is_prime(n): result = False for divisor in range(2,math.sqrt(n)): if n % divisor == 0: result = True break # breaks out of nearest for or while return result def fibonacci(n): if "something about n": #base case return "what base value?" else: return "what result of a recursive step?"