Functions¶
A function is like a recipe, a series of steps that the computer will follow. But we’ve been giving the computer steps to follow all along! What is different about a function? The important thing about functions is that they have names, inputs, and outputs.
Let’s imagine that you have this program to add two numbers:
a = 10
b = 20
c = a + b
print(c)
It works! But what if you want to add more than once? You’d have to write something like:
a = 10
b = 20
c = a + b
print(c)
a = 5
b = 6
c = a + b
print(c)
With a function, we can stop repeating ourselves. Let’s make a function for addition:
def add(a, b):
c = a + b
return c
print(add(10,20))
print(add(5,6))
Notice that the important part of the addition procedure is now inside the
function. The def
keyword says that we are going to define a fuction, and the
variables in the parentheses, (a,b)
are called the argument list. Those are the inputs to
the function.
The last line, return c
is the output from the function. That is the value that we want to print.
Notice that you’ve already seen functions, we’ve been using them all along. Here is part of the first program we made:
tina = turtle.Turtle()
tina.shape('turtle')
Try running this program and see what you get.
Now re-write the program to multiply the two numbers.
You can have a different number of arguments for the input to the function. Re-write it again to multiply three numbers.
Make Five Cakes¶
Earlier we talked about how functions are like recipes. In this exercise,
we’ve already taught Tina the recipe for making a picture of a cake and she’s
made three. Tell her to make more cakes by calling the function with
different x
and y
locations at the very bottom of the program.
How many cakes should she make?
Hint: The first number in make_cake()
is how far left or right Tina should go, while the second is how high or low she should go before starting to draw.
Run this program, then change the program how ever you want. Some things you can try:
Change the colors of the cakes
Make the cakes bigger
Put the cakes in different places
Use a loop to make more cakes
Functions and Loops¶
Let’s update a square function one more time. This time remove the redundancy in the program with a loop, but also use a function; your loop should run a function many times, and the function should draw part of the square.
When your program is correctly drawing a square, try changing the variable to see what other shapes you can make.
Thanks to Trinket.io for providing the 5 cakes assignment, part of their [Hour of Python] (https://hourofpython.com/a-visual-introduction-to-python/) course.