Moods Are Contagious
- Editorial Expression of Concern and Correction
- Facebook Tinkers With Users’ Emotions in News Feed Experiment, Stirring Outcry
Test Review
Reading Questions
Quiz
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(): turtle.forward(100) turlte.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(dist): turtle.forward(dist) turtle.left(90)
Now, it can be called like this
draw_something(10)
- This is much like the turtle functions we have already used…
turtle.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
If a function has multiple parameters, then the order of the arguments is the same
def draw_something(dist, angle): turtle.forward(dist) turtle.left(angle) draw_something(10, 20)
In this case,
dist
has the value 10 andangle
has the value 20 because the parameterdist
is before the parameterangle
Function Comments
- Functions allow you to write code that is isolated from other code
- This is great because it facilitates testing by making the amount of code to be tested small and managable
- It also facilitates code sharing and reuse
- It is easy to reuse a function by copying it from one file into another or importing it
- It also provides a distinction of responsibility for different people to contribute to a program
- To make using functions easier for other people, need to specify under what conditions it will succeed
For example the above function draw_something will break if it is called with strings for input
draw_something('a little bit')
To inform the user of a function of its limitations, use a comment
# dist (number) - distance the turtle will move def draw_something(dist): turtle.forward(dist) turtle.left(90)
These limitation are often on type, but can also be on the values that are allowed for a particular type