Professional Documents
Culture Documents
Introduction to
Programming
Week 3
Adding new functions
HEADER
def print_lyrics():
print “I’m a lumberjack, and I am okay.”
print “I sleep all night, and I work all day.”
Adding new functions
BODY
def print_lyrics():
print “I’m a lumberjack, and I am okay.”
print “I sleep all night, and I work all day.”
Adding new functions
• Defining a function creates a variable with the same name.
def print_lyrics():
print “I’m a lumberjack, and I am okay.”
print “I sleep all night, and I work all day.”
print_lyrics()
def repeat_lyrics():
print_lyrics()
print_lyrics()
repeat_lyrics()
Flow of execution
• Execution starts from top, and proceeds to bottom
in order.
• Function definitions do not alter the flow of
execution. However, a function is not executed
unless called explicitly.
• A function call is like a detour in the flow of
execution.
Parameters and Arguments
def print_twice(x):
print x
print x
print_twice(‘ENGR 211’)
Variables and Parameters
are Local
def student(first,last):
full = first + ‘ ’ + last
print_twice(full)
name1 = ‘red’
name2 = ‘kit’
student(name1, name2)
print full
Local Variables
def print_twice(x):
print x
print x
print full
Why Functions?
• make a program smaller by eliminating repetitive
code.
• write once, debug, and reuse many times
• if you make a change, you only have to make it
in one place.
>>> int(’32’)
>>> int(‘hello’)
>>> int(‘2.39’)
>>> float(32)
>>> str(32.45)
Math functions
X
TurtleWorld
• Several turtle-steering functions:
• fd(a_turtle, x): move a_turtle forward x units
• bk(a_turtle, x): move a_turtle backward x units
• lt(a_turtle, angle): make a_turtle turn left by angle
• rt(a_turtle, angle): make a_turtle turn right by angle
• Each Turtle is holding a pen. If the pen is down, the
Turtle leaves a trail when it moves.
• pu(a_turtle): make a_turtle’s pen up
• pd(a_turtle): make a_turtle’s pen down
TurtleWorld
# import everything in TurtleWorld module
from swampy.TurtleWorld import *
# build a world of turtles
world = TurtleWorld()
# maybe, a little turtle, Bob, is born here!
bob = Turtle()
for i in range(4):
print ‘Hello’
• Use a for loop to draw the square.
for loop – syntax
for i in range(4):
fd(bob,100)
lt(bob)
wait_for_user()
Exercises
square(bob)
Encapsulation
• Encapsulation?
• Wrapping a piece of code up in a function
• Benefits?
• You re-use the code. It is more concise to call a
function twice than to copy and paste the body!
• Easy maintenance: Just need to modify the
function definition. Function calls will directly be
affected by the modification.
Encapsulation
# encapsulation demo
ray = Turtle()
square(ray)
Ex 2
square(bob, 100)
Generalization
• Generalization?
• Adding a new parameter to a function
• Benefits?
• It makes the function more general:
• in the previous version, the square is always
the same size;
• in this version, it can be any size.
Generalization
Next step: instead of drawing squares, draw regular
polygons with any number of sides.