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
defis the keyword (a word with a special meaning in Python) that makes a function. Python knows only this word:fnorfuncwill not work. If you already know JavaScript: Python usesdef, notfunction.total_priceis the function's name, written in snake_case (lowercase words joined by underscores). Inside the brackets are the parameters: names for the values that will be sent in, herepriceandquantity. On the recipe card, the parameters are the blanks. Thedefline ends with a colon.- The indented lines below
defare the function body. The body does not run yet when Python readsdef. Python only stores the recipe. total_price(15, 3)calls the function: this is when the body runs. The values sent in a call are called arguments: they fill the blanks on the card. Herepricegets 15 andquantitygets 3, in that order.returnhands the result back to the place where the function was called, then the function ends. If the body has more lines belowreturn, those lines never run.- Because the result is handed back, you can use a function call like any value. In this code, the result of the first call is printed directly. The results of the next two calls are added, then stored in the variable
bill.
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
45is printed by theprintinside the function, when the function is called.- The function ends without a
return. A function with noreturnalways returnsNone, a special value that means "nothing in it". SoresultholdsNone, and the second line printsNone. - As a result,
total_price(15, 3) + 5fails with aTypeError, becauseNonecannot be added to a number.
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
quantity=1means: if the caller does not say how many, assume 1 cup.- Parameters without a default must be written before the ones that have a default. Python refuses
def total_price(quantity=1, price):withSyntaxError: parameter without a default follows parameter with a default.
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.
- A docstring is different from a
#comment. Python ignores a comment, but keeps a docstring ingreet.__doc__. The built-in functionhelp(greet)shows it. - Editors also show it while you type the function's name. So other people know how to use the function without reading its body.
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 parameter and
return(the fix above, used in this lesson): the function only uses the values you send in, then sends its result back withreturn. So it is easy to see wheretotalchanges. global totalas the first line inside the function: Python uses thetotaloutside, so afteradd(15),totalholds15. That is enough for a small script. But any function can changetotal, so when the value is wrong, it is hard to find which function caused it.- An object attribute, for example
order.total: the value is stored inside an object (a container that keeps data and functions together). This is covered in the lesson Classes & Objects.
⚠️ A None that appears suddenly, and other function errors
- Confusing
printwithreturn. The function prints a number, but the value it returns isNone. If you need the result again, usereturn. - Too few arguments. When
quantityhas no default,total_price(15)fails withTypeError: total_price() missing 1 required positional argument: 'quantity'. - Calling before
def. You getNameError: name 'total_price' is not defined. Put thedefabove the call. - Changing an outside variable from inside a function.
total += priceinside a function ends withUnboundLocalError. Send the value in through a parameter, thenreturnthe result.
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.