Software Design Fall 2004 For next time: 1) Finish Homework 2 2) Read Chapter 3 of the Olinux manual Recurtle, part 2 ---------------- On paper, sketch what you think this program will draw, then type in the code and try it. def draw(t, dist, n): if n == 0: return fd(t, dist*n) lt(t, 45) draw(t, dist, n-1) rt(t, 90) draw(t, dist, n-1) lt(t, 45) bk(t, dist*n) world.clear() bob = Turtle(world) bob.delay = 0.1 lt(bob) draw(bob, 10, 3) You might want to adjust the value of bob.delay to get a better view of what is going on. Also, try increasing or decreasing the value of the parameter n. Where is the turtle when the draw function finishes? Draw a stack diagram that shows the state of this program at one of the instants when n==0. Two ways to think about functions --------------------------------- 1) mechanism how does parameter passing work? how do return values work? 2) abstraction think of a function as a black box (inputs, outputs, side-effects) think of user-defined functions the same way you think of built-ins Example: distance between turtles def distance(x, y): blah blah blah def inter_turtle_distance(t1, t2): dx = t1.x - t2.x dy = t1.y - t2.y dist = distance(dx, dy) myrtle = Turtle(world) yertle = Turtle(world) print inter_turtle_distance(myrtle, yertle) Example: read tree abstractly # tree draws a tree with n levels of recursion # postcondition: the turtle ends up back where it started def tree(t, dist, n): if n == 0: return fd(t, dist*n) lt(t, 45) tree(t, dist, n-1) rt(t, 90) tree(t, dist, n-1) lt(t, 45) bk(t, dist*n) Can we prove that turtle ends up back where it started? Rules of return --------------- 1) a return statement all by itself ends the current function 2) a return statement with a value ends the current function and provides a return value 3) a function that doesn't provide a return value returns None >>> def fun(): ... x = 5 ... >>> fun() # just invoke the function >>> print fun() # invoke the function and print the result None >>> print fun # print the function object By convention, most functions either 1) always return None (sometimes called void functions) 2) always return a non-None value (called fruitful) def abs(x): if x<0: return -x elif x>0: return x What's wrong with abs? Encapsulation ------------- Type in the following program or cut and paste it from wb/sd/notes/notes05.txt world.clear() bob = Turtle(world) bob.delay = 0.001 bob.x = -150 bob.y = 90 bob.redraw() def koch(t, n): if n<5: fd(t, n) return n = n/3.0 koch(t, n) lt(t, 60) koch(t, n) rt(t, 120) koch(t, n) lt(t, 60) koch(t, n) for i in range(3): koch(bob, 300) rt(bob, 120) Improve it by: 1) encapsulating the last three lines in a function 2) refactoring koch For more information, Google "koch curve", or check out http://www.jimloy.com/fractals/koch.htm