Functions 0/2

Lesson 6 of 21

Defining new functions

Write a small function once and call it again: powers, swaps, primes, digit sums and GCD.

Part 1 of 9 Repeated code

Writing the same lines again

Every program you have written so far runs each of its lines once, from the top down. Real programs often need the same steps more than once. Say you are writing a quiz that prints two lines of instructions before each of its three questions. With what you know so far, you have to write those two lines out three times:

Sign up to run
print("Answer with one number.")
print("You have 30 seconds.")
print("Question 1: 6 * 7")
print("Answer with one number.")
print("You have 30 seconds.")
print("Question 2: 9 - 13")
print("Answer with one number.")
print("You have 30 seconds.")
print("Question 3: 15 % 4")

This works until the instructions change. If the time limit becomes 20 seconds, you have to edit every copy, and if you miss one, the quiz tells the player two different limits.

Often the copies are not even identical. Suppose each round gets shorter: 30 seconds for the first question, 20 for the second and 10 for the third. Now the copies differ in one number, and you still write each one out by hand.

We want to write the two lines once, give them a name, and run them by that name wherever the quiz needs them, with a different number each time. A function lets you do that. Another way to repeat lines is the loop, which suits steps that run one after another; here the instructions are spread between the questions, so a function fits better.

The quiz instructions as a function

Here is the quiz with a function. The two lines are written once, under the name instructions, and the number of seconds, which is different in each round, gets a name of its own, seconds:

Sign up to run
def instructions(seconds):
    print("Answer with one number.")
    print("You have", seconds, "seconds.")

instructions(30)
print("Question 1: 6 * 7")
instructions(20)
print("Question 2: 9 - 13")
instructions(10)
print("Question 3: 15 % 4")

The first three lines are the function definition. def instructions(seconds): says that a function named instructions starts here, and the indented lines under it are its body. Defining the function prints nothing. The body runs when you call the function by writing its name and parentheses, as in instructions(30), the same way you called abs and max. seconds is a parameter: a name for the value that changes from call to call. The 30 in instructions(30) is that call's argument, so while that call runs, seconds is 30, and during the next call it is 20.

The program prints the nine lines of the quiz, now with limits of 30, 20 and 10 seconds. The instructions are written once, so if their wording changes, you edit one place.

Definition

A function definition gives a name to a block of code and lists its parameters. A call runs the block, with each parameter holding the matching argument.