Cool Computer Science Thing of the Day
Reading Questions
Quiz
Emacs Tip of the Day
- M-/ auto complete
Writing Functions
- We know how to use functions…
print
,turtle.forward
,math.cos
- Functions are named code, they do something
We can define our own named code
def draw_something(): alex = turtle.Turtle() alex.forward(100) alex.left(90)
- Execute the function just like other functions,
draw_something()
Note, order matters, you can’t use it until you have defined it, just like a variable
Parameters and Arguments
- Note that the previous example creates a new turtle every time it is executed
- We can fix this if by having the function share the same turtle across multiple executions.
- To do this we need to give the function input, the turtle to use
Parameters are variables with a value set outside of the function
def draw_something(t): t.forward(100) t.left(90)
Now, it can be called like this
alex = turtle.Turtle() draw_something(alex)
- This is much like the turtle functions we have already used…
alex.forward(100)
, the 100 is the input to the function, it changes the behavior of the function - The names of the inputs, in the function definition, are called parameters
The names of the inputs, in the function call, are called arguments
Pre and Post Conditions
What if when calling a function you give an argument that doesn’t make sense?
draw_something(100)
- The function breaks, because it is expecting a turtle, not a number
- This is a common mistake, to help prevent it we add comments above the function describing the conditions in which the function is guaranteed to work correctly
Also need to specify the effects of the function as a post condition
# PRE: t is a turtle object # POST: draws a line and turns 90 degrees def draw_something(t): t.forward(100) t.left(90)