Functions
A function groups instructions under a name. Parameters receive values when the function is called. The body runs only when you call the function.
Define reusable code with parameters and return a result.
Example check: Worked and guided code samples are checked against CPython 3.13. Practice uses Pyodide 0.29.5 (Python 3.13) in your browser. How we check lessons
Video lesson: Functions
The preview is stored on this site. YouTube loads only when you press Play. Watch on YouTube
Jump to a chapter
Read the video transcript
Select a timestamp to watch that moment on YouTube.
- 00:00
A function gives a useful set of instructions a name. Instead of copying a calculation for every new value, you define it once and call it with the value you need. Today we will build square, follow two calls through the same body, and distinguish what a function returns from what it prints. That distinction matters because a printed number can appear on screen while the caller still receives no usable result. We will then add a default argument, reject an invalid input with an early return, and let one function call another. These are not tricks to make code look sophisticated. They are ways to give each small piece of work a clear purpose.
- 00:40
Open the Functions lesson if you want to pause and run each example in the console. Before you press Run, ask where execution will go next and which value the caller will receive. That prediction is the skill that makes functions feel predictable instead of mysterious. The line beginning with def creates a function named square. The name value inside the parentheses is a parameter: a local name that will refer to the argument supplied by a caller. The indented body multiplies that value by itself and returns the product. At definition time, Python records those instructions but does not execute the body.
- 01:20
Execution enters the body when it reaches square called with four. For that call, value is four, so the expression returns sixteen. The caller stores sixteen in answer, and the following print displays it. A second call with seven uses the same body but a new local value, and prints forty-nine. The two calls do not overwrite one another's arguments. The return statement ends that call and passes a value back. We can use the returned value in another calculation, an assignment, or a print call. A greeting function on the lesson page uses the same pattern for text: it receives a name, builds a message, and returns the message.
- 02:02
A function can also provide a default for a parameter. The shipping example has a fee of five unless the caller supplies a different fee. Calling shipping_total with twenty alone returns twenty-five. Calling it with twenty and a named fee of zero returns twenty. A default makes the common case short while preserving control for exceptional cases. Look at the discount example next. It first checks whether the percent is below zero or above one hundred. If either invalid condition is true, it returns the message Invalid discount immediately. No discounted-price calculation follows for that call. For a valid twenty-percent discount on fifty, the calculation subtracts one fifth of the original and formats Price: forty dollars.
- 02:50
An early return makes a bad input's route visible before the normal route. Finally, consider the receipt example. receipt_line gets an item and a price, then calls price_with_tax to perform the numerical calculation. The returned taxed price is formatted into a readable line. For a ten-dollar notebook at an eight-percent rate, the output is Notebook: ten dollars and eighty cents. A two-dollar pen becomes two dollars and sixteen cents. This is composition: a larger task built from smaller functions with clear inputs and outputs. It is easier to test price_with_tax separately than to debug one giant receipt function.
- 03:32
There is no rule that every function needs many lines. A short function is valuable when its name explains a meaningful operation and it can be reused or tested on its own. Pause here and predict what happens if the shipping fee is two instead of five. Trace which argument fills which parameter before checking the console. The classic function mistake is to print the answer inside the function when the caller needs the answer back. If double prints eight and has no return statement, the call displays eight as a side effect but returns None. Save that call in result and print result, and you will see eight followed by None. That is not Python losing the number.
- 04:14
The function never handed the number to the caller. Change print to return inside double; now the caller receives eight and can store or use it. Printing is for display, returning is for delivering a value to the caller. Another common error is calling greet without a name when its definition requires one. Python raises TypeError because the required argument is missing. Read the function signature, then supply one argument for each required parameter. Defaults can make some parameters optional, but only when you define them that way. Also remember that parameters are local names. Assigning a new number to value inside square does not automatically rename a variable in the caller.
- 04:59
When a function behaves unexpectedly, write down its arguments, the path through its body, its return statement, and the resulting value at the call site. That four-step trace usually identifies whether the problem is in the call or the function. For your practical task, define double with one parameter and return two times that parameter. Call it with nine and print the returned result. Predict eighteen before running. Then save the result in a variable and print that variable to confirm it is a usable value, not merely a line that appeared on the screen. Press Check Task when the code works. For a second experiment, call double with zero and a negative number.
- 05:43
The same function body still applies, and the outputs reveal whether your understanding covers more than the single example. The quiz asks you to evaluate a returned square, identify what a function returns when it has no explicit return, and explain what a parameter receives. If any answer feels uncertain, write the smallest possible function in the console and check. Next we will use classes to group data and the functions that operate on that data inside objects.
Understand the concept
return sends a value back to the caller. print only displays a value; it does not make that value the function's result. Names created inside a function are normally local to it.
- Define with def
- Pass arguments into parameters
- return a reusable result
See it step by step
Read the code, predict the output, then compare it with the result.
01. Return a greeting
def greet(name):
return f"Hi, {name}!"
print(greet("Maya"))Hi, Maya!The argument Maya becomes the local name parameter. return sends the finished string back to print().
02. Reuse a calculation
def triple(number):
return 3 * number
print(triple(4))
print(triple(7))12
21One function can be called with different arguments without repeating the calculation.
A closer look
Follow the reasoning, inspect each result, then try the suggested changes in the console below.
Defaults simplify the common call
A parameter can have a default value. The caller may omit that argument for the common case and supply it when a different case is needed. In a shipping calculation, a standard fee can be the default, while pickup can pass zero. The parameter is local to each call: using a different fee once does not permanently change the function's default.
Put parameters without defaults before parameters with defaults, so a call remains unambiguous. Choose defaults that are stable and unsurprising; if a value varies with current data, passing it explicitly may be clearer. Predict the result of shipping_total(20, 2), then call the function with that second argument in the console.
def shipping_total(subtotal, fee=5):
return subtotal + fee
print(shipping_total(20))
print(shipping_total(20, fee=0))25
20- The first call uses the default fee of 5.
- The second call overrides fee for that call only.
Return early when a value is invalid
A function may have several return statements. Once Python reaches one, that call ends; statements below it are not executed. This makes a guard at the beginning useful: reject an invalid input before doing the normal calculation. The main path then stays less indented and easier to read. Decide what an invalid input should mean before writing the function.
This example returns a message for an impossible percentage. A larger application might instead raise an exception, which you will study later. The important point here is that every intended path returns a result the caller can handle. Try discount_label(50, -1) and discount_label(50, 100); predict both results before running them.
def discount_label(price, percent):
if percent < 0 or percent > 100:
return "Invalid discount"
final_price = price * (1 - percent / 100)
return f"Price: ${final_price:.2f}"
print(discount_label(50, 20))
print(discount_label(50, 120))Price: $40.00
Invalid discount- 20 passes the guard, so the discounted price is calculated.
- 120 fails validation; the early return ends that call.
Build a larger answer from small functions
A useful function can call another function. One function calculates a value; another decides how to present it. This separates a calculation from the words on a receipt and gives each part one job. If the tax rule changes, you can change the calculation without rewriting every receipt line. Returning values makes this kind of composition possible.
Notice that the helper does not print anything. It gives its answer to receipt_line(), which formats the label. That means the calculation can also be reused by other code. Before running, predict how many lines appear when receipt_line() is called twice. Then change the tax rate to 0.10 and compare the prices.
def price_with_tax(amount, rate):
return amount * (1 + rate)
def receipt_line(item, price):
final = price_with_tax(price, 0.08)
return f"{item}: ${final:.2f}"
print(receipt_line("Notebook", 10))
print(receipt_line("Pen", 2))Notebook: $10.80
Pen: $2.16- receipt_line() calls price_with_tax() and receives a number.
- It formats that number to two decimal places and returns text.
- Only the two outer print() calls produce output.
Try it in Python
Edit the example and run it. Python starts in your browser the first time you click Run.
Python console
Ready to runNeed input()? Add one value per line
Your output appears here.
Need a hint?
Define def double(value): and return value * 2 from inside it. After the definition, call double(9) inside print().
Complete the task and select Check task to verify your code.
Quick quiz
Three questions. You can change your answers and try again.
Typical mistakes
Everyone meets these errors. See what causes them and how to fix them.
Printing instead of returning
def double(value):
print(value * 2)
result = double(4)
print(result)def double(value):
return value * 2
result = double(4)
print(result)What happens: The function prints 8, but result is None.
Use return when callers need to store or reuse the calculated value.
Missing required argument
def greet(name):
print(f"Hi, {name}")
greet()def greet(name):
print(f"Hi, {name}")
greet("Maya")What happens: TypeError because name was not supplied.
Provide one argument for each required parameter.