…
…
Python Programming Fundamentals · Lesson 14 / 40 · Functions
PreviewIn this lesson you will
return, call it with different arguments, and use the returned value in another calculationreturn gives back NoneYou can read the explanation without an account. The exercises and quiz at the end of the lesson are for members.
In Corner Café's till program, the total with sales tax is written in three separate places with the same formula: for the latte, for the cookie, and for the tea. Ada realized that if the tax rate changes, she would have to fix all three lines one by one, and if she forgets one, the receipt will be wrong. In this lesson you will write your own function: you write the calculation once and call it by name.
The program you write by the end of the lesson will print this receipt:
OutputLatte x2: $9.35
Cookie x3: $6.60
Tea x4: $5.50So far you have used Python's ready-made functions such as print, round, max, and len. In lesson 5 you saw that a function is called by its name and parentheses, that you give it arguments, and that it produces a result. In this lesson you will do the same thing the other way around: you describe the job, Python gives that description a name, and you call that name as often as you like.
In this lesson you will:
def and call it with different arguments.return and use it in another calculation.print and return, and recognize a function that returns None.First look at today's version of the till program.
Example 1a (case): The repeated version
latte = 4.25 * 2 * 1.1 print(f"Latte x2: ${latte:.2f}") cookie = 2.00 * 3 * 1.1 print(f"Cookie x3: ${cookie:.2f}") tea = 1.25 * 4 * 1.1 print(f"Tea x4: ${tea:.2f}")
OutputLatte x2: $9.35
Cookie x3: $6.60
Tea x4: $5.50The program works correctly; the problem is elsewhere. The pattern price * qty * 1.1 is written three times. If the tax rate went up to 20 percent, you would have to find 1.1 in three lines and change it to 1.2. In a real till program, this calculation also appears on the receipt, in the end-of-day report, and on the refund screen; the number of lines grows to dozens. If you forget one, the program gives no error; it quietly prints a wrong amount. The solution is to write the calculation in one place and give it a name. That name is called a function.
A function is defined with the word def. After def come the function's name, the parameters in parentheses, and a colon at the end of the line. The indented lines under it are the function's body; as in an if block, they are indented with four spaces. Parameters are empty boxes that get filled each time the function is called. The naming rules are the same as for variables: lowercase letters, underscores between words. It is a good habit to choose a name that says what the function does: total_with_tax, print_receipt, calculate_discount.
A definition alone calculates nothing; it only saves the recipe. For the body to run, you have to call the function: write its name and put the values in the parentheses. The values in the call are called arguments. At the moment of the call, Python puts the arguments into the parameter boxes in order, runs the body from start to finish, and brings the result to the place where the call was made.
Example 1b (case): The lesson's target program
# 1. Write the recipe def total_with_tax(price, qty): """Return the total with tax from price and quantity.""" return price * qty * 1.1 # 2. Call it for each item and print print(f"Latte x2: ${total_with_tax(4.25, 2):.2f}") print(f"Cookie x3: ${total_with_tax(2.00, 3):.2f}") print(f"Tea x4: ${total_with_tax(1.25, 4):.2f}")
OutputLatte x2: $9.35
Cookie x3: $6.60
Tea x4: $5.50The output is exactly the same as Example 1a, but now the formula stands in one place. In the call total_with_tax(4.25, 2), 4.25 goes into the price box and 2 goes into the qty box; the body calculates 4.25 × 2 × 1.1, and the result is placed inside the f-string. In the second call, the same boxes are filled with 2.00 and 3. We will come back to the triple-quoted description on the first line of the body in a moment.
Test this analogy right away. In the program below, a function is defined and then one line is printed. Predict what you will see on the screen without running the code.
What appears on the screen when this program runs?
def greet(): print("Welcome to Corner Café") print("Till is open")
To see with your own eyes what happens at the moment of the call, step through the code below. There are three things to watch. First, when the def line runs, only the name amount is created; the body is not entered. Second, on the line amount(4.25, 2), the flow jumps up into the body and the price and qty boxes are filled. Third, on the return line, the flow goes back to the line where the call was made and the result is put in the latte box. In the second call, the same boxes are filled again, this time with 1.25 and 3. After stepping through, use "Change the code" to change the line tea = amount(1.25, 3) to tea = amount(1.25, 4) and see how the result changes.
Run the code line by line: see which line runs next, the variable boxes and the output.
def amount(price, qty): result = price * qty return result latte = amount(4.25, 2) tea = amount(1.25, 3) print(latte + tea)
Think of why you bother to define a function like this: if you are about to write a calculation for the second time, that calculation wants to be a function. Fixing a calculation that stands in one place is a one-line job; also, the function's name tells whoever reads the code what those lines do.
return: giving the result backThe return line gives the value the function produced back to the caller. The call expression turns into that value; it is as if the value itself were written in the code in place of the call. So you can put the returned value in a variable, print it, or use it directly inside another calculation. For example, on the line to_pay = total_with_tax(4.25, 2) + 1, Python first runs the call, takes the returned 9.35 (with its floating-point remainder), adds 1, and puts the result in the to_pay box.
The second job of return is to end the function. The moment return runs, the function stops there, and the lines below it are never reached. At first this looks like a limitation, but it turns into a useful pattern: you catch a special case at the start of the function and return a value right away, and the remaining code runs only for the general case. This is called an early return.
Example 2 (case): A discount with an early return
def discount(amount): if amount >= 10: return amount * 10 / 100 return 0 print(discount(12.5)) print(discount(7.5)) print(discount(10))
Output1.25
0
1.0For an order of $12.50, the condition is true; the first return gives back 1.25 and the function ends. The line return 0 is never reached, so you do not need to write else. For 7.5, the condition is false, the if block is skipped, and the second return gives 0. 10 is a boundary value: since >= accepts equality too, the discount is given. A function can have more than one return, but in each call only one of them runs.
In the block below, change the order amount and see which return line runs: the line that does not run appears faded. Notice one more thing: the name of the function's parameter is amount, while the name of the variable given in the call is order. The two names do not have to be the same. At the moment of the call, Python copies not the name of the variable but the value inside it into the parameter box.
Change the order amount: which return runs?
Pick a value; predict the output first, then look.
1def discount(amount):2 if amount >= 10:3 return amount * 10 / 1004 return 056order = 12.57print("Discount:", discount(order))
Discount: 1.25
Faded lines didn't run with this value. At 7.5, the condition is false, line 3 is skipped, and the return 0 on line 4 runs. At 10 and 12.5, line 3 runs and the function ends there; line 4 stays faded. The value of the order variable is copied into the amount parameter; it makes no difference that the names are different.
Now test with a prediction that return ends the function. In the function below, there is one more line under return.
What does this program print on the screen?
def double(amount): return amount * 2 print("Calculated") print(double(20))
print shows, return givesThis is the pair that beginners mix up most, because both seem to let you see something on the screen. But the jobs they do are completely different. print writes the value on the screen and the job ends there; the program cannot use that value again, because the value is now only on the screen, in front of your eyes. return, on the other hand, gives the value back to the program; the program can store it, add it up, compare it. The return line writes nothing on the screen; if you want to see it on screen, you print the returned value on the caller's side.
So what does a function with no return at all give back? Python has to put a value in place of every call. If a function ends without ever meeting return, Python puts None there. Remember from lesson 8: None means "no value".
print(result) | return result | |
|---|---|---|
| What it does | Writes to the screen | Gives the value to the caller |
| The function's return value | Does not change (None if there is no return) | result |
| Can the result be used in another calculation | No | Yes |
| Does it end the function | No | Yes |
Example 3 (case): One prints, one returns
def print_total(latte, cookie): print(latte + cookie) def total(latte, cookie): return latte + cookie a = print_total(4.25, 2.00) b = total(4.25, 2.00) print(a, b)
Output6.25
None 6.25The 6.25 on the first line was printed by the print inside print_total; this is a side effect that appears on the screen while the function runs. But since print_total has no return, None is put in the a box. total, on the other hand, writes nothing on the screen; it gives back 6.25 and the b box is filled with 6.25. The last line prints what is inside the two boxes: None 6.25. Do not let seeing 6.25 twice on the screen mislead you: one was only shown, the other was really obtained.
The rule is simple: a function that calculates returns the result, and the caller does the printing. This way the same total_with_tax can be used on the receipt, in the end-of-day report, and in the discount calculation. If there were a print inside the function, the result would stay only on the screen. Now test it with a prediction.
What does the last line print?
def greet(name): print("Hello", name) result = greet("Ada") print(result)
Now you know all the parts of a function. Match each part of Example 1b with its name.
What is the name of each part of Example 1b?
For each row, pick its match from the list, then check.
defprice (in the definition line)4.25 (in the call)total_with_tax(4.25, 2)return"""Return the total with tax ..."""help, and testing a functionIn Example 1b, the first line of the body was a sentence between triple quotes: """Return the total with tax from price and quantity.""" This is called a docstring (documentation string). A docstring calculates nothing; it briefly explains what the function takes and what it returns. It is not seen only by whoever reads the code: in lesson 5 you read the description of a ready-made function with help(abs). You can do the same for your own function; help brings the docstring you wrote to the screen.
Example 4 (case): Ask `help` about your own function
def total_with_tax(price, qty): """Return the total with tax from price and quantity.""" return price * qty * 1.1 help(total_with_tax)
OutputHelp on function total_with_tax in module __main__:
total_with_tax(price, qty)
Return the total with tax from price and quantity.The first line says this is a function and that it was defined in your program (__main__). The second line is the signature: the function expects two values, price and qty. The third line is your description. Weeks later, you coming back to this program, or a friend who takes over the code, can learn from here what the function does without reading the body. Write a docstring for every function, even a short one.
The body of a function does not have to be a single line. Everything you learned in earlier lessons (variables, if, for, counters) works inside the body too. However long the body is, the function gives out only one thing: the value that return gives back. Put the lines below in the right order: first the definition line, then the docstring, then the body, and last the main code that uses the function.
Put the lines of the program that splits the bill among people in order. The program must print 4.17.
Click the lines in order; to undo one you placed wrong, click it in the list below.
Shuffled lines
Your order
Your work is not finished when you write a function. Right away, call it with two or three different arguments and compare the result with the value you calculated by hand. Try boundary values too: exactly $10 as in Example 2, or 0 for the quantity. Do not assume that because a function gives one correct result, it works correctly in every case. In lesson 19 you will make the program do these checks itself; for now, doing them by hand is enough.
Now it is your turn. In the cell below, Example 1b is ready. (1) Add a line for a brownie: price $2.75, quantity 2; your output should be Brownie x2: $6.05. (2) The tax rate became 1.2 instead of 1.1: how many lines did you have to change? How many lines would the same change have affected in the repeated version of Example 1a? (3) Add help(total_with_tax) at the bottom and run it, then change the docstring to your own sentence and run it again.
Try it now· not graded; doesn't affect progress
A function is not a tool specific to a café. A weather app uses this formula to convert degrees Celsius to Fahrenheit: multiply the degrees by 9, divide by 5, add 32. We write the recipe once and call it with three different temperatures.
def fahrenheit(celsius): """Convert degrees Celsius to Fahrenheit.""" return celsius * 9 / 5 + 32 print(fahrenheit(100)) print(fahrenheit(0)) print(round(fahrenheit(36.6), 1))
Output212.0
32.0
97.9On the last line, the returned value was given directly to round: fahrenheit gives back 97.88, and round rounds it to one decimal place. A returned value can be the argument of another function; this would not be possible with print.
The body can contain a loop and a condition too. This function uses the counter pattern from lesson 12 to count the lowercase vowels in a word and returns the count.
def count_vowels(word): """Count the lowercase vowels in a word.""" count = 0 for letter in word: if letter : count += 1 count (count_vowels()) (count_vowels())
Printing the result instead of returning it. If you use print inside the function and assign its result to a variable, you see the number on the screen, but the variable becomes None. The next calculation then crashes:
def subtotal(price, qty): print(price * qty) latte = subtotal(4.25, 2) print(latte * 2)
On the screen:
Output8.5
Traceback (most recent call last):
File "<kod>", line 5, in <module>
print(latte * 2)
~~~~~~^~~
TypeError: unsupported operand type(s) for *: 'NoneType' and 'int'Read the message from the end: NoneType and int cannot be multiplied. NoneType is the type of None; there is None in the latte box, because subtotal returned nothing. Do not let the 8.5 on the screen mislead you; it was printed by the print inside the function. The right way: write return price * qty in the body and leave the printing to the caller.
Calling a function before defining it.
def name(parameters): binds an indented body to a name but does not run it; the call name(arguments) puts the arguments into the parameter boxes in order and runs the body. A function must be defined before it is called.return gives the value back to the caller and ends the function at that moment; the returned value takes the place of the call and can be used in another calculation. Of several return lines, only one runs in each call (early return).print only writes to the screen; a function without return gives back None. A function that calculates returns the result, and the caller does the printing.Next lesson: We will call the same function sometimes with a single item and sometimes with a discount: default and keyword arguments.
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.
Output4
3The line return count is outside the loop, at the indentation of the body; so it runs once, after the loop has gone through all the letters. If you had written return inside the loop, the function would end at the first letter. You will learn to count capital letters too in the string methods lesson.
print(total_with_tax(4.25, 2)) def total_with_tax(price, qty): return price * qty * 1.1
On the screen:
OutputTraceback (most recent call last):
File "<kod>", line 1, in <module>
print(total_with_tax(4.25, 2))
^^^^^^^^^^^^^^
NameError: name 'total_with_tax' is not definedThe function is in the file, but when line 1 runs, the def line has not been reached yet. The right way: collect the definitions at the top of the program and write the main code that uses them at the bottom.