…
…
Python Programming Fundamentals · Lesson 15 / 40 · Functions
PreviewIn this lesson you will
You can read the explanation without an account. The exercises and quiz at the end of the lesson are for members.
In the previous lesson you moved the repeated calculation at Corner Café's till into a function. Ada likes functions, but she has a complaint: most orders are a single item with no discount, yet she has to write price_calc(4.25, 1, 0) in every call, and a week later, when she looks at the code, she cannot remember what that 0 was. In this lesson you will teach functions to say "if nobody says otherwise, do the usual", and you will learn to give arguments by name.
The price function in the previous lesson had three parameters: price, quantity, and discount. All three were required; if you left one out, Python raised a TypeError. But at the till, things look like this: the price is different in every order, but the quantity is usually 1 and there is usually no discount. Writing 4.25, 1, 0 every time is tiring and hard to read. Someone reading the line price_calc(4.25, 1, 0) can find out what the 1 and the 0 are only by looking at the definition.
At the end of the lesson you will call the same function in four different ways, and you will be able to state these four results yourself before running anything:
Output4.25
12.75
3.4
4.0In this lesson you will be able to:
Recall two words from the previous lesson. A parameter is a name inside the parentheses of the definition (price and quantity in the line def price_calc(price, quantity):). An argument is the value sent to that parameter in the call (4.25 and 2 in the call price_calc(4.25, 2)). When a function is called, each parameter opens like a box and one argument is put into it. The whole topic of this lesson is the answer to this question: which argument goes into which box, and what happens if no argument arrives for a box?
To make a parameter optional, you write = and a value after its name in the definition: quantity=1. This is called a default value. The rule is simple: if no argument is given for that parameter in the call, the default value is put into the box; if an argument is given, the given value is put in and the default is never used. A default value is a backup; it does not overwrite the value you give.
In fact, you have already met a default value. In lesson 5 you read the description of built-in functions with help(); if you type help(round), you see round(number, ndigits=None) in the first line. The ndigits=None there is the default value of the second parameter. That is why, when you write round(4.678), no number of digits is given, and the result is rounded to an integer: 5. When you write round(4.678, 1), the second argument takes the place of the default and the result is 4.7. The same function, two different ways of calling it.
Now let's apply the same idea to the till function. The discount is given as a percentage: 20 means 20 percent. That is why we multiply the price by (100 - discount) / 100.
Example 1 (case): One definition, four calls
# 1. The recipe: quantity and discount are optional def price_calc(price, quantity=1, discount=0): """The discount is given as a percentage (20 = 20 percent).""" return price * quantity * (100 - discount) / 100 # 2. Four different calls print(price_calc(4.25)) print(price_calc(4.25, 3)) print(price_calc(4.25, discount=20)) print(price_calc(quantity=2, price=2.00))
Output4.25
12.75
3.4
4.0Let's see in a table how the boxes are filled in each call:
| Call | price | quantity | discount | Result |
|---|---|---|---|---|
price_calc(4.25) | 4.25 | 1 (default) | 0 (default) | 4.25 |
price_calc(4.25, 3) | 4.25 | 3 | 0 (default) | 12.75 |
price_calc(4.25, discount=20) | 4.25 | 1 (default) | 20 | 3.4 |
price_calc(quantity=2, price=2.00) | 2.00 | 2 | 0 (default) | 4.0 |
In the first call only the price was given; the defaults were put into the quantity and discount boxes. In the second call the second argument, 3, went to the second parameter, quantity, and took the place of the default 1. All the results are floats, because the formula contains /, and / always gives a float. We will talk about the discount=20 and quantity=2 forms in the third and fourth calls shortly.
Follow the small receipt function below step by step. In each call, look at which value fills the item, qty, and price boxes when the function body is entered: which came from the call, and which from the default?
Run the code line by line: see which line runs next, the variable boxes and the output.
def receipt(item, qty=1, price=1.25): return f"{qty} x {item} = ${qty * price:.2f}" print(receipt("tea")) print(receipt("latte", 2, 4.25)) print(receipt("water", price=0.75))
In the second call the price box became 4.25, not 1.25. There is a common misunderstanding here: some students think the default value always applies and overwrites the value they gave. The opposite is true: the default only takes effect if the box stays empty. Try it yourself. Change the quantity and rate values below and see how the result changes.
Change the quantity and rate values: which box stays at its default, and which one takes the value you give?
Pick a value; predict the output first, then look.
1def price_calc(price, quantity=1, discount=0):2 return price * quantity * (100 - discount) / 10034quantity = 15rate = 06print(price_calc(4.25, quantity, discount=rate))
4.25
Faded lines didn't run with this value. Every value you give goes into the box and takes the place of the default: when you choose rate = 20, the discount becomes 20 and the default 0 is never used. With rate = 0, the result is the same as not writing the discount at all, because the default is also 0. The return line in the body of the function (line 2) runs every time.
With rate = 0 selected, the call discount=rate gives the same result as not writing the discount at all: 4.25. The reason is that the default value is also 0. But when you choose rate = 20, 20 goes into the box and the default 0 is never used.
So far you have always given arguments in order: the first argument goes to the first parameter, the second argument goes to the second parameter. This kind of argument is called a positional argument, because its position (its order) decides where it goes. A positional argument is short to write, but it has two problems. First, you cannot skip a parameter in the middle: to give the discount, you have to write the quantity too. Second, the person reading the call has to know by heart what each value is.
The solution is the named argument: in the call you give the argument with the name of the parameter, like discount=20. Python puts this value into the box named discount, without looking at the order. This gives you three things. You can skip the ones in the middle: when you write price_calc(4.25, discount=20), quantity stays at its default. You can leave the order free: price_calc(quantity=2, price=2.00) is valid, because each value finds its own box by its name. Most importantly, the call explains itself: nobody asks what the 20 is on the line that says discount=20.
Now let's check the most common mistake. The cashier wants to give a 20 percent discount on a latte and hurriedly writes the line below.
The cashier wanted to give a 20 percent discount. What does this code print?
def price_calc(price, quantity=1, discount=0): return price * quantity * (100 - discount) / 100 print(price_calc(4.25, 20))
This example shows why a named argument is not just a convenience. In a positional call, a wrong order does not raise an error; it silently produces a wrong result. A receipt for $85.00 of lattes is noticed only when the customer objects. Named arguments prevent this kind of mistake from the start.
The second common misunderstanding is thinking that the order still matters when you give arguments by name. Below is a function that divides the bill by the number of people; the arguments are given in the reverse order of the definition, but with their names.
What does this code print?
def split(bill, people): return bill / people print(split(people=2, bill=10))
Python's own functions also use named arguments, and you were already working with them without noticing. For example, print has two named parameters. sep decides what goes between the values when you print more than one; its default is a space. That is why print("Total:", 5) prints with a space in between. end decides what goes at the end of the line; its default is a new line. That is why every print starts on a new line. If you want to change these two parameters, you give them by name. When you write your own functions, you will follow the same pattern.
Example 2 (case): Receipt line
def receipt_line(item, price, qty=1, symbol="$"): return f"{qty} x {item}: {symbol}{price * qty:.2f}" print(receipt_line("Tea", 1.25)) print(receipt_line("Latte", 4.25, 2)) print(receipt_line("Latte", 3.5, 2, symbol="€")) print(receipt_line(symbol="£", item="Water", price=0.5))
Output1 x Tea: $1.25
2 x Latte: $8.50
2 x Latte: €7.00
1 x Water: £0.50This function has two required parameters (item, price) and two optional ones (qty, symbol). The third call uses both ways together: the first three arguments are given in order, and the currency symbol by name. In the fourth call all the arguments are named and in mixed order; since qty was never given, it stayed at 1. The price has no default, because every item has a different price: if a call forgets the price, we want it to raise an error rather than silently print a wrong receipt.
Example 3 (outside the case): Named arguments in Python's own functions
print("08", "30", sep=":") print("Loading", end="...") print("done") print("Latte", "Tea", "Water", sep=" | ") print(round(3.14159, ndigits=2))
Output08:30
Loading...done
Latte | Tea | Water
3.14In the first line, a colon was put between the two values instead of a space, and the time format came out. In the second line, end="..." took the place of the new line; that is why the next print continued on the same line and "done" was written right after it. In the last line we gave the second parameter of round by name; it gives the same result as round(3.14159, 2), but it tells the reader that 2 is the number of digits. Thinking that "named arguments only exist in functions I write myself" is wrong: most of Python's built-in functions are adjusted this way.
Change the separator yourself and watch the output:
Change the separator: what does sep put between the two values?
Pick a value; predict the output first, then look.
1separator = ":"2print("08", "30", sep=separator)
08:30
Faded lines didn't run with this value. The named argument sep decides the text that goes between the values. When you choose " ", the output is as if sep had not been written: the default of sep in print is a single space.
Now that you can use positional and named arguments together, let's put the way Python matches them into rules. Two rules are for the definition line, and two are for the call.
| Where | Rule |
|---|---|
| In the definition | Parameters with a default value are written after those without one |
| In the call | Positional arguments come first, then named arguments |
| In the call | Every parameter is filled exactly once: a required parameter that is never filled, or a parameter that is filled twice, is an error |
| In the call | The name of a named argument must be exactly the same as the parameter name in the definition |
Python first distributes the positional arguments to the parameters in order, from left to right. Then it places the named arguments by their names. At the end, it puts the default values into the boxes that are still empty. If a box without a default is still empty, or if two values want to go into one box, it stops the call and tells you why.
The reason for the definition rule also comes from this way of distributing. Imagine you wrote def total(quantity=1, price):. In the call total(4.25), 4.25 goes in order into the first box, that is, quantity, and the required price stays empty. Python catches this ambiguity in the definition line itself and does not run the program at all. That is why the idea "I can put the parameter with a default in any order I like" is wrong.
Now let's look at the real messages Python gives when each rule is broken. Read the messages from the end, as in lesson 5: the last line tells you the type and the cause of the error, and the price_calc() part tells you which function's call has the problem.
Outputprice_calc(quantity=2)
TypeError: price_calc() missing 1 required positional argument: 'price'
price_calc(4.25, 2, 10, 5)
TypeError: price_calc() takes from 1 to 3 positional arguments but 4 were given
price_calc(4.25, price=2.00)
TypeError: price_calc() got multiple values for argument 'price'
price_calc(4.25, discnt=10)
TypeError: price_calc() got an unexpected keyword argument 'discnt'. Did you mean 'discount'?
price_calc(discount=10, 4.25)
SyntaxError: positional argument follows keyword argument
def total(quantity=1, price):
SyntaxError: parameter without a default follows parameter with a defaultHere is what the messages mean. "missing 1 required positional argument: 'price'": the required price argument is missing. "takes from 1 to 3 positional arguments but 4 were given": this function takes 1 to 3 positional arguments, and you gave 4. "got multiple values for argument 'price'": price got two values; 4.25 had gone to price in order, and then price=2.00 wanted to fill the same box again. "got an unexpected keyword argument 'discnt'": there is no parameter named discnt. Python 3.14 adds a suggestion to the end of this line (the closest parameter name, discount). The last two are SyntaxErrors: Python stops while reading the line, before running it. One says that a positional argument was written after a named argument, and the other says that a parameter with a default was written first in the definition.
Match the messages with their causes. This is exactly what you will do when you meet an error.
Match each error message with its cause.
For each row, pick its match from the list, then check.
missing 1 required positional argument: 'price'takes from 1 to 3 positional arguments but 4 were givengot multiple values for argument 'price'got an unexpected keyword argument 'discnt'positional argument follows keyword argumentparameter without a default follows parameter with a defaultLet's see the rules together in the cinema ticket example. The two optional parameters of this function take True or False.
Example 4 (outside the case): Cinema ticket
def ticket(age, student=False, weekend=False): if age < 12: fee = 3 elif student: fee = 4 else: fee = 6 if weekend: fee += 1 return fee print(ticket(30)) print(ticket(20, student=True)) print(ticket(8, weekend=True)) print(ticket(20, True, True))
Output6
4
4
5In the third call we skipped the student parameter and gave only the weekend; we could not have done this without a named argument. The last call also works within the rules and gives the right result, but True, True tells the reader nothing: which one is student, and which one is weekend? ticket(20, student=True, weekend=True) gives the same result (5) in a readable form. Calling parameters that take True/False by name is a good habit.
Reinforce the rules by building a program. Put the lines below in the right order: a coffee function with medium as the default size is defined and called with a named argument for the large size. The output should be 5.0.
Put the lines in the right order: define the function and call it for the large size. The output should be 5.0.
Click the lines in order; to undo one you placed wrong, click it in the list below.
Shuffled lines
Your order
One last note: when you look at built-in functions with help as in lesson 5, you sometimes see a / or * mark in the signature (the output of help(abs) says abs(x, /)). These marks limit whether an argument can be given in order or by name; you can ignore them for now.
When you write your own function, you decide which parameter gets a default value. A useful guide:
| Question | Decision |
|---|---|
| Is it different in every call (price, item name, age)? | Make it required, give no default; write it first |
| Is it the same in most calls (quantity 1, discount 0, symbol $)? | Give it a default; write it last |
Does it take True/False? | Give it a default and give it by name when you call |
Giving a default to a value that changes in every call is dangerous. If you write price=4.25, a call that forgets the price does not raise an error; it calculates every item at the latte price. A required parameter is a parameter that speaks up when it is forgotten. On the other hand, making an almost unchanging value required means unnecessary typing and calls that are hard to read.
Something you may wonder: how can print take as many values as you want? The way to do it is to put * in front of a parameter name (*args); the incoming values are collected in a structure called a tuple. You will see tuples in lesson 29; until then this is just a note.
Now you have a working function. In the cell below, try these three things in order: (1) Add a new call for a brownie ($2.50). (2) Write the same line using only named arguments, mixing the order; is the result the same? (3) In one of the calls, write symb= instead of symbol=, press Run, read the last line of the message, and undo the mistake.
Try it now· not graded; doesn't affect progress
The value a function returns can be used in another calculation. We add up the total of an order with three items, calling each item in the shortest readable way: two lattes, three cookies with a 10 percent discount, and a single tea.
def price_calc(price, quantity=1, discount=0): return price * quantity * (100 - discount) / 100 total = 0 total += price_calc(4.25, 2) total += price_calc(2.00, 3, discount=10) total += price_calc(1.25) print(f"Total: ${total:.2f}")
OutputTotal: $15.15Both parameters have defaults, so the function can be called with no arguments at all. In the body, the end parameter of print lines the numbers up on the same line with a space after each one; the print after the loop writes the message and ends the line.
def count_down(start=3, message="Go!"): for number in range(start, 0, -1): print(number, end=" ") print(message) count_down() count_down(5, message="Liftoff!")
Output3 2 1 Go!
5 4 3 2 1 Liftoff!Writing `==` instead of `=` in a named argument. Once you are used to writing == in conditions, the same sign comes to your finger in the call too:
print(price_calc(4.25, discount==20))OutputNameError: name 'discount' is not definedThe message is surprising: discount exists in the definition, so why does it say "not defined"? Because discount==20 is not a named argument, it is a comparison. Python first looks for a variable named discount, and since there is no such variable where the call is, it stops. The name discount exists only inside the function, when the box is opened. The right way is a single equals sign: price_calc(4.25, discount=20). In a named argument, = means "put this into this box"; do not confuse it with ==, which asks about equality.
quantity=1 in the definition is optional: if no argument is given, the default is used, and if one is given, the given value is used; parameters with defaults are written after those without.discount=20) sits by its name; a named argument lets you skip the ones in the middle, leaves the order free, and makes the call readable. The sep and end of print are also named arguments.TypeError or SyntaxError message of a call that breaks the rules tells you which parameter has the problem.Next lesson: The number of functions has grown; in the next lesson we will learn why a variable inside a function is not visible from outside, and we will split a long program into parts.
Exercises and quiz are for members
This lesson has 6 coding exercises and a 10-question quiz. Sign up free to solve them, save your progress and move on to the next lesson.