Give Each Job a Name with Functions

As a program grows, the same few lines start to appear in several places: the same greeting, the same calculation, the same check. A function lets you write those lines once, give them a name, and run them whenever you need them by writing that name. You can hand a function values to work with, and it can hand a result back. This page explains how to define a function, how values travel into it and out of it, and what happens to the names you create inside it.

Defining a function and calling it

You have already used functions that come with Python, such as print, input and len. Writing a name followed by round brackets, like len(scores), is called calling the function: it tells Python to run the function now. A function of your own works the same way once it exists. You create it with a definition, which starts with the keyword def.

A definition, then two calls
def say_hello():
    print("Hello!")
    print("Ready to start?")

print("Before")
say_hello()
say_hello()

The first line of the definition is def, then the name you choose, then round brackets and a colon. The lines under it, indented like the block of an if or a loop, are the body: the instructions the name stands for.

The key point is what Python does when it reads the definition. It does not run the body. It only remembers the body under the name say_hello, and moves on. The body runs each time the function is called, and only then. So this program prints Before first, and then the two lines of the body twice, once for each call:

Before
Hello!
Ready to start?
Hello!
Ready to start?

Because Python reads a file from top to bottom, a definition has to come before the first call of the function. Calling a name Python has not seen yet stops the program with an error.

True or false?

A program that only defines a function with def, and never calls it, prints nothing from that function.

True. The definition only stores the body under the name. The body runs when a call such as say_hello() is reached.

Calling the same function three times runs its body only once, the first time.

False. Every call runs the whole body again, from its first line.

Parameters and arguments

A function that always does exactly the same thing is of limited use. Most functions need some values to work with: whose name to greet, which numbers to add. You say which values a function expects by writing names between its round brackets in the definition. These names are its parameters.

When you call the function, you put values between the brackets of the call. These values are the arguments. At the start of the call, Python gives each parameter the argument that belongs to it. Inside the body, each parameter then works like a variable that refers to its argument. So the parameter is the name, fixed in the definition, and the argument is the value, which can be different in every call.

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

greet("Ana", "Hi")
greet("Sam", "Welcome")
Hi, Ana!
Welcome, Sam!

By position or by name

In the calls above, the arguments are matched by position: the first argument goes to the first parameter, the second to the second. Swap them, as in greet("Hi", "Ana"), and Python does what you wrote, not what you meant: it prints Ana, Hi!.

You can also pass an argument by name, writing the parameter name, an equals sign and the value. Python then matches it by that name, so the order no longer matters:

greet(greeting="Welcome", name="Sam")   # Welcome, Sam!
greet("Sam", greeting="Welcome")        # Welcome, Sam!

The second call mixes both ways. That is allowed as long as the arguments by position come first and the ones by name follow.

Python also checks that every parameter gets exactly one value. The program stops with a TypeError that names the function when a call leaves out an argument the function needs, when it passes more arguments than the function has parameters, or when it gives the same parameter two values.

True or false?

greet(name="Ana", greeting="Hi") and greet(greeting="Hi", name="Ana") print the same line.

True. Arguments passed by name are matched to parameters by their names, so their order in the call does not matter.

The parameters of a function and the arguments of a call are two words for the same thing.

False. Parameters are the names written in the definition. Arguments are the values a call passes in for them.

Parameters with a default value

Sometimes one argument is the same in almost every call. Instead of writing it every time, you can give its parameter a default value in the definition, with an equals sign. A call that leaves that argument out gets the default; a call that passes it gets the value it passed.

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

greet("Ana")                   # Hello, Ana!
greet("Ana", "Good morning")   # Good morning, Ana!
greet("Ana", greeting="Hi")    # Hi, Ana!

A parameter with a default is optional. A parameter without a default is required, and leaving it out is an error.

In the definition, the parameters with a default come after the ones without, so def greet(name, greeting="Hello") is fine and def greet(greeting="Hello", name) is a syntax error. That order lets Python match the arguments by position without guessing which one you skipped.

True or false?

With def greet(name, greeting="Hello"), the call greet("Ana", "Hi") prints Hello, Ana!

False. The default is used only when the call leaves the argument out. Here the call passes "Hi", so it prints Hi, Ana!

Handing a result back with return

Many functions exist to work something out: a total, a percentage, a tidied string. The part of the program that called the function, the caller, wants that result so it can store it, print it or compute with it. The return statement hands it back.

def percent(correct, total):
    return round(correct / total * 100)

score = percent(3, 4)
print(score)               # 75
print(percent(1, 3) + 1)   # 34

When Python reaches return, it works out the value after it, ends the call at once and gives that value back. Any lines in the body after a return that runs are skipped.

Back in the caller, the call itself stands for the value it returned. So percent(3, 4) becomes 75, and score = percent(3, 4) stores 75. In the last line, percent(1, 3) becomes 33, and 33 + 1 is printed.

  • Caller
  • percent
  • Caller to percent: arguments 3, 4
  • percent to percent: correct = 3, total = 4
  • percent to Caller: return 75

To predict what a call gives back, follow the arguments: put each one in place of its parameter, work through the body to the return that runs, and compute the value after it.

Predicting calls of percent(correct, total)
CallcorrecttotalGives back
percent(3, 4)3475
percent(4, 3)43133
percent(total=8, correct=6)6875
percent(1, 3)1333

No return gives back None

Every call gives something back. A function whose body ends without reaching a return, or that uses return with nothing after it, gives back None: a special Python value that means "no value". say_hello and greet above return None, which is fine, because they are called for what they show and not for a result.

Returning is not printing

The two are easy to confuse because both can make a number appear on the screen. print shows text to the person running the program, and the program cannot use that text afterwards. return gives a value to the caller, and shows nothing on its own. Compare two functions that both double a number:

Prints the result
def show_double(n):
    print(n * 2)

a = show_double(5)   # shows 10
print(a)             # None
Returns the result
def double(n):
    return n * 2

b = double(5)        # shows nothing
print(b)             # 10

show_double(5) puts 10 on the screen, but it hands back None, so a is None and a + 1 would fail. double(5) hands back 10, which the caller can store, add to or print as it likes. A function that computes something is usually more useful when it returns the result and leaves the printing to the caller.

True or false?

A function that prints a number inside its body also returns that number to the caller.

False. print only shows text. Without a return, the call gives back None.

When a return line runs, the lines of the body below it are not run in that call.

True. return ends the call at once and hands the value back to the caller.

With def double(n) returning n * 2, the line x = double(double(3)) stores 12.

True. The inner call becomes 6, and double(6) becomes 12.

Names inside a function are local

A function body can create variables of its own, to hold a step of the work. Here ratio holds the division before it is turned into a percentage:

def percent(correct, total):
    ratio = correct / total
    return round(ratio * 100)

print(percent(3, 4))   # 75
print(ratio)           # NameError

The parameters (correct and total) and every variable assigned in the body (ratio) are local variables: they belong to one call. They are created when the call starts and disappear when it ends, so each call gets its own fresh set of names. Only the returned value leaves the function.

That is why the last line fails. After the call, it asks for a name that no longer exists, and Python stops with a NameError saying that the name ratio is not defined. To use a result outside, return it and store it, as in score = percent(3, 4).

This is what makes functions safe to use in many places. A local name cannot clash with a name in the rest of the program: if the program also has its own variable called ratio, assigning ratio inside the function creates a separate local one and leaves the outer one unchanged. And because every call starts fresh, nothing left over from one call changes the next.

True or false?

After percent(3, 4) has run, the program can read the variable total and get 4.

False. total is a parameter, so it is local to the call and is gone when the call ends.

Two functions can each use a local variable called result without affecting each other.

True. Each call has its own local names, so the two result variables are separate.