Introductory Programming Fall 2004 For Thursday you should 1) Finish Homework 5. 2) Read Chapters 6 and 7 if you haven't. Quick review of fruitful functions ---------------------------------- Some functions have side effects, but don't return anything. def square(t, d): for i in range(4): fd(t, d) lt(t) You invoke them like a statement... square(bob, 100) Some functions return values. def distance(t): return (t.x*t.x + t.y*t.y)**0.5 You invoke them like an expression: dist = distance(bob) print d OR print distance(bob) Number 1 most common mistake that you will make 100 times before you stop doing it: Invoking a fruitful function without doing anything with the result. Example: distance(bob) This is a semantic error, because it compiles and runs... and does nothing! while loops ----------- Try this: s = 'allen' i = 0 while i < len(s): print i, s[i] i = i + 1 s is a string, which is a compound object (because it contains elements) i is an integer, which is being used here as 1) a loop variable 2) an index The assignment statement i = i + 1 looks funny (especially if you still think of it as a mathematical statement) The elements of a string are numbered starting at 0. Encapsulation and generalization -------------------------------- Create a file named filters.py and add the following code: s = 'allen' i = 0 while i < len(s): print s[i] if s[i] == 'e': print 'eureka!' break i = i + 1 In a sequence of steps, we are going to rewrite this code as a function that takes a string as a parameter and returns True or False, depending on whether the string contains the letter 'e'. 1) wrap the existing code in a function named has_e, and run the program 2) now add a line of code that invokes the function, and run the program 3) now change the program so that has_e takes a string s as a parameter WARNING: when you make changes like this, you have to change the definition of the function AND the place where it is invoked. 4) now change has_e so that instead of printing 'eureka' if it finds an e, it returns the value True WARNING: you have just changed a fruitless function into a fruitful function, which means that you have to invoke it differently 5) what happens to code that appears after a return statement? 6) change the value of the argument string to a word that does not contain an e. What happens if a function gets all the way to the end without returning anything? 7) change the program so that if it gets all the way through the word without finding an e, it returns False. Test the function twice, once with and once without an e. 8) change has_e so that it doesn't print anything. It should ONLY return True or False. In general, most fruitful function don't have side effects; they only return a value. That's why, if you don't do anything with the return value, nothing happens! 9) how could you change has_e to make it a more general function?