CodeRigor

LESSON

Write functions and finish a complete program

Name a step as a function with parameters and a return value, then combine variables, input, decisions and loops into one complete interactive program.

You have been using functions since the first lesson: print, input, int, float and range are all functions that somebody else wrote. In this lesson you write your own, and then put everything from this unit together in one complete program.

A function is a named step

A function is a block of statements with a name. You write the block once, and then run it whenever you like by using the name.

Writing the block is called defining the function. Running it is called calling it.

Python
def show_welcome():
    print("Welcome to the quiz!")
    print("Type your answers and press Enter.")

show_welcome()
print("Round two.")
show_welcome()

This prints the two welcome lines, then Round two., then the two welcome lines again.

The definition starts with the word def, then the name, round brackets and a colon. The indented block underneath is the function's body.

Defining a function does not run its body. Python only remembers it. The body runs each time the function is called, which is what the lines show_welcome() do. The brackets are what make it a call.

Parameters let a function work on different values

A function is far more useful when you can hand it values to work with. A parameter is a variable named in the brackets of the definition. When you call the function, you give a value for each parameter. Those values are the arguments.

Python
def greet(name):
    print(f"Hello, {name}!")

greet("Ada")
greet("Grace")

This prints Hello, Ada! and Hello, Grace!. In the first call the parameter name refers to "Ada"; in the second it refers to "Grace".

A function can have several parameters, separated by commas. The arguments are matched to them by position: first to first, second to second.

return hands a value back

print shows something to the user. Often you want a function to work something out and give the result back to the rest of the program instead. That is what return does.

Python
def area(width, height):
    return width * height

floor = area(3, 4)
print(floor)
print(area(2, 5) + 1)

This prints 12 and 11.

When Python reaches return, the function stops and the value after return takes the place of the call. So area(3, 4) becomes 12, and the assignment names it floor. A call that returns a value can be used anywhere a value can: in a calculation, in a condition, inside an f-string.

One call, there and back
start / 5 ⇄ code
The arguments travel in and become the parameters. The body runs. return sends one value back to the place the call was written.
One call, there and back
The arguments travel in and become the parameters. The body runs. return sends one value back to the place the call was written.

The parameters and any variables created inside a function exist only while that call is running. width and height cannot be used outside area. The way to get a result out of a function is return.

print or return?

They look similar when you are experimenting, and they are not the same thing.

Python
def double_and_print(n):
    print(n * 2)

def double(n):
    return n * 2

result = double_and_print(4)
print(result)
print(double(4) + 1)

This prints 8, then None, then 9.

double_and_print shows 8 on the screen but returns nothing. A function that reaches its end without a return gives back a special value called None, which means "no value". That is what result holds. double shows nothing by itself, but it returns 8, which the program can go on to use.

As a rule: functions that work something out should return it. Let the main part of the program decide what to print.

Functions can contain everything you know

A body can hold decisions and loops. As soon as a return runs, the function is finished, so each path can return its own answer.

Python
def ticket_price(age):
    if age < 5:
        return 0
    elif age < 16:
        return 5
    else:
        return 9

print(ticket_price(3))
print(ticket_price(12) + ticket_price(40))

This prints 0 and 14.

Python reads a program from the top, so a function must be defined above the first line that calls it. The usual layout is: function definitions first, then the main part of the program.

A complete program

Here is a small but complete program: a three-question multiplication quiz. It uses every idea in this unit. Read it from the top, then run it in the Python playground with three answers in the standard input box, for example 14, 20 and 28.

Python
# A three-question quiz on the 7 times table.

def is_correct(a, b, answer):
    return a * b == answer

score = 0
for a in range(2, 5):
    answer = int(input(f"What is {a} x 7? "))
    if is_correct(a, 7, answer):
        print("Yes!")
        score += 1
    else:
        print(f"No, it is {a * 7}.")

print(f"Score: {score} out of 3")

With the answers 14, 20 and 28 the session is:

Text
What is 2 x 7? 14
Yes!
What is 3 x 7? 20
No, it is 21.
What is 4 x 7? 28
Yes!
Score: 2 out of 3
How the quiz program is put together
start / 4
The function is defined first and used inside the loop. The loop repeats the prompt, read, decide, print shape three times, and a running total carries the score out of the loop.
How the quiz program is put together
The function is defined first and used inside the loop. The loop repeats the prompt, read, decide, print shape three times, and a running total carries the score out of the loop.

Notice how the function gives a name to one step, "is this answer correct?". The loop then reads almost like a sentence.

Two errors you will meet

The wrong number of arguments.

Python
def area(width, height):
    return width * height

print(area(3))
Text
Traceback (most recent call last):
  File "main.py", line 4, in <module>
    print(area(3))
          ~~~~^^^
TypeError: area() missing 1 required positional argument: 'height'

The last line names the function and the parameter that was given no value. Line 4 is the call to repair: area needs two arguments.

Forgetting return. There is no error message for this one, which makes it harder to spot.

Python
def area(width, height):
    width * height

print(area(3, 4))

This prints None. The body works out 12 and then throws it away, because nothing says return. When you see None where you expected a value, look for a missing return.

What you can do now, and where to go next

You can define a function with parameters, return a result from it, and build a complete interactive program from variables, input, decisions, loops and functions. That is the core of programming in any language. The capstone build asks you to write one more complete program: a number-guessing game.

When you have finished it, continue with the next unit of this course, which starts at names, objects and copying. It moves faster than this unit and assumes exactly what you now know. From there the course goes on to functions in more depth, lists and dictionaries, and handling errors.

Watch & read

Free lectures, talks and readings that cover this skill from another angle. All resources →

Starts at 'Defining Functions' (1:26:14) and continues through 'Return Values' to the end of the lecture: writing your own function, why it must be defined before it is called, and returning a result. About twenty minutes.