Software Design Fall 2004 For next time: 1) finish hw03 2) read Chapter 9 of "How to think..." An early bird special --------------------- eval is a built-in function that takes a string and evaluates it using (of all things) the Python interpreter Try this: >>> eval('2+2') 4 >>> eval('eval') >>> eval('eval("2+2")') 4 >>> eval('eval("eval")') Why doesn't this work? >>> eval('print "hello"') There is an example of eval in my hw01 solutions: def keypress(event): # this function gets called when the user presses a key try: # figure out which function to call, and call it func = eval('draw_' + event.char) func(bob, size) skip(bob, size/2) except NameError: print "I don't know how to draw an", event.char except SyntaxError: # this happens when the user presses return teleport(bob, -180, bob.y-size*3) Strings ------- Strings are immutable s = 'allen' print capitalize(s) print replace(s, 'n', 'n downey') Note that these methods return new strings; they don't modify strings, because... STRINGS ARE IMMUTABLE. Strings are compound objects, which means that they contain items. What is an index? An integer expression used to identify an item in a compound object. What is a slice? A pair of indices that identify a subsequence of a compound object. for i in range(len(s)): print i, s[i] What's the difference between a = b and a = b[:] string.constants ---------------- the string module defines some constants, like >>> print string.punctuation !"#$%&'()*+,-./:;<=>?@[\]^_`{|}~ >>> print string.ascii_lowercase abcdefghijklmnopqrstuvwxyz >>>print string.lowercase that are useful for testing characters Exception Handling ------------------ run-time errors are also known as exceptions normally when an exception occurs, Python: 1) prints a traceback 2) prints an error message 3) ends the program If you do something that might cause an error, you can "catch" the exception: def singular(x, y): try: res = x / y except: res = 10000.0 return res In this example, there is no great advantage over using an if statement. What's the difference between string.find and string.index? LOOK BEFORE YOU LEAP res = string.find('apple', 'pl') if res == -1: print "didn't find it" else: print "found it at index", res BETTER TO ASK FORGIVENESS THAN PERMISSION def myfind(s, sub): try: res = string.index(s, sub) return res except: print "didn't find it" return -1 Once you add try statements to your toolbox, you will start seeing uses for them.