Python Functions

def name(parameters): makes a function (a named block of code). Its body only runs when the function is called with name(arguments): the arguments are the…

In Mr. Darto's till program, the formula price * quantity appears in many places: for coffee with milk, for sweet tea, for every customer. One day the formula changes. For example, a charge for the cup is added. You have to find every place and change each one. If you miss one, the total in that place is different from the others.

It is tidier to write the formula once, give it a name, and call it (run it by its name) whenever you need it. That is a function: a block of code with a name, so you can call it again and again without writing it again. A function is like a recipe card in the stall's kitchen: "Total price: the price times the number of cups". The card is written once, then used for every customer. The blanks on the card (what the price is, how many cups) are filled in each time the card is used. The result is then handed back to the till.

Making and calling a function

This function calculates the total price, and below it are two ways to use it:

def total_price(price, quantity):
    return price * quantity

print(total_price(15, 3))                             # 45
bill = total_price(5, 2) + total_price(12, 1)
print(bill)                                           # 22

A function must be made with def before it is called. Python runs the file from top to bottom. So a call written above its def fails with NameError: name 'total_price' is not defined.

return and print are different

Imagine the cashier asks an assistant to calculate a total. The cashier is the code that calls, and the assistant is the function. An assistant who uses print shouts the number across the stall. Everyone hears it, but the cashier has nothing in hand. An assistant who uses return writes the number on a piece of paper, then gives the paper to the cashier. So the cashier can use the number again.

The function below uses print, not return. Guess first: two lines are printed. Is the second line 45 or None?

def total_price(price, quantity):
    print(price * quantity)

result = total_price(15, 3)
print(result)

The output:

45
None

The rule: a function that calculates something should return its result. Let the code that calls the function do the printing.

Default parameters

You can give a parameter a default value with =. If its argument is not sent, the default value is used:

def total_price(price, quantity=1):
    return price * quantity

print(total_price(12))         # 12, quantity uses the default 1
print(total_price(15, 3))      # 45, quantity is 3

In this lesson's exercise you calculate a price after a discount, for example 10% off $100. The discount is 100 * 10 / 100, which is 10.0. So the final price is 100 - 10.0 = 90.0. Remember from the operators lesson: / always gives a float (a number with a decimal point). That is why Python writes 90.0, not 90.

Docstring

A docstring is a string on the first line of a function body, written with triple quotes. It explains what the function does:

def greet(name):
    """Greets a customer by name."""
    return f"Hello, {name}!"

print(greet.__doc__)   # Greets a customer by name.

Variables inside a function

A variable made inside a function only exists inside that function. It is called a local variable. For example, subtotal in this code:

def total_price(price, quantity):
    subtotal = price * quantity
    return subtotal

total_price(15, 3)
print(subtotal)   # NameError: name 'subtotal' is not defined

Outside the function, the name subtotal is not known, so the last line fails.

A variable made outside every function can be read from inside a function. But if the function changes it with = or +=, Python treats that name as a new local variable of the function, not as the outside one. In this example, total += price means total = total + price. That line has to read the local total first, but the local total has no value yet:

total = 0

def add(price):
    total += price

add(15)

The result is an error:

UnboundLocalError: cannot access local variable 'total' where it is not associated with a value

The cleanest fix: send the value in through a parameter, return the new value, then store that result outside the function. The function becomes def add(total, price): return total + price, and the call becomes total = add(total, 15).

There are three ways to solve this problem:

⚠️ A None that appears suddenly, and other function errors

TL;DR: def name(parameters): makes a function (a named block of code). Its body only runs when the function is called with name(arguments): the arguments are the values you send, and the parameters are the names that receive them. return hands the result to the caller and ends the function. A function with no return returns None, so a print inside a function does not replace return. A default parameter (quantity=1) is used when its argument is not sent, and is written after the parameters without a default. / gives a float: 100 - 100 * 10 / 100 is 90.0. A docstring ("""...""" on the first line of the body) explains the function and can be read with help(). Variables made inside a function are local: they only exist inside that function. Changing a variable made outside the function with += from inside it causes UnboundLocalError.

⚡ Write it once, call it many times

Write:

def total_price(price, quantity):
    return price * quantity

print(total_price(15, 3))                             # 45
bill = total_price(5, 2) + total_price(12, 1)
print(bill)                                           # 22

Meaning: def is the keyword (a word with a special meaning in Python) that makes a function, not function or fn. price and quantity are parameters: names for the values that will be sent in. The function body (the indented line) does not run yet when def is read. total_price(15, 3) calls the function with two arguments: price gets 15 and quantity gets 3, in that order. return hands the result back to where the function was called.

⚡ print isn't return

Write:

def total_price(price, quantity):
    print(price * quantity)

result = total_price(15, 3)
print(result)
Guess first: is the second printed line 45 or None?

None. The first line, 45, is printed by the print inside the function. But the function doesn't return anything, so result holds None.

Meaning: A function with no return always returns None. A function that calculates something should return its result.

⚡ A default value

Write:

def total_price(price, quantity=1):
    return price * quantity

print(total_price(12))         # 12, quantity uses the default 1
print(total_price(15, 3))      # 45, quantity is 3

Meaning: quantity=1 gives quantity a default value of 1, which is used when no argument is sent for quantity. Parameters without a default must be written before the ones that have a default.

⚡ Variables inside a function

Guess first: subtotal is made inside the function. Does print(subtotal) outside the function work?

No. Outside the function the name subtotal is not known, so you get NameError: name 'subtotal' is not defined.

Meaning: A variable made inside a function is local: it only exists inside that function. If you need its value outside, return it.

What you will learn