Lesson explanation
After this lesson, you will be able to:
A function packages reusable behavior behind a name. Define it with def, list the required parameters inside the parentheses, and indent the function body:
def calculate_total(price, quantity):
return price * quantityprice and quantity are parameters. The values supplied in a call such as calculate_total(12.5, 4) are arguments.
The most important distinction in this lesson is return versus print(). print() displays a value, but return sends a result back to the caller. Returned values can be stored, compared, formatted, passed to another function, or checked by automated tests.
A function can return different kinds of values, including strings, numbers, and booleans. When a condition identifies a final result, an early return can end the function immediately and avoid unnecessary nesting.
If execution reaches the end of a function without a return, Python returns None.
💡 Tip: In a
function_task, Hintor calls your function with several test cases. Return the result; printed text does not replace a returned value.
The caller receives the calculated value and can reuse it.
def estimate_storage(file_size_mb, copies):
return file_size_mb * copies
required_mb = estimate_storage(18, 3)
print(f"Storage: {required_mb} MB")Output:
Storage: 54 MBThe function calculates; the caller decides how to display the result.
Parameters make the helper reusable for different values.
def format_environment(name, region):
return f"{name.lower()}@{region.upper()}"
print(format_environment("Staging", "eu"))Output:
staging@EUThe returned string is built from both arguments.
A comparison can be returned directly.
def is_within_limit(used, limit):
return used <= limit
print(is_within_limit(72, 100))Output:
TrueThe result is a boolean, not the text "True".
An early return handles the blocking case before the normal result.
def deployment_status(failed_checks, is_frozen):
if is_frozen:
return "frozen"
if failed_checks > 0:
return "blocked"
Output:
readyOnce Python reaches a return, the function ends immediately.
return will not run.Python for Developers
Assembled code
Generated code is hidden by default. Expand it only if you want to inspect what your current blank values produce.
0 / 6 tasks completed
| Goal | Python |
|---|
| Define reusable behavior | def function_name(parameters): |
| Send a result to the caller | return value |
| Display a value only | print(value) |
| End a function when a rule is final | Early return |
| No explicit returned value | Python returns None |