Python & data · Lesson 07
Functions and return values
Give a reusable operation a name, pass it inputs, and return a result.
- Define and call a function
- Distinguish parameters from arguments
- Return a value to the caller
Helpful background: Understand variables, decisions, and loops.
Define and call a function
A function groups instructions under a name. def introduces the function, followed by parameters in parentheses and an indented body.
The body runs when you call the function. An argument is the value passed to a parameter in that call.
def greet(name):
print(f"Hello, {name}!")
greet("Mira")
greet("Sam")Return a result
return sends a value back to the caller and ends the function. Printing shows a value; returning lets the caller store it, combine it, or test it.
A function that reaches the end without an explicit return returns None.
def area(width, height):
return width * height
room_area = area(4, 3)
print(room_area) # 12Defaults and names
A parameter can have a default used when the caller omits that argument. Local names created inside a function are separate from names in the caller.
Avoid using a mutable object such as a list as a default argument unless you intend to share it between calls.
def greeting(name, prefix="Hello"):
return f"{prefix}, {name}!"
print(greeting("Mira"))
print(greeting("Sam", prefix="Welcome"))Keep responsibilities clear
Give a function one clear job and a name that describes it. Test normal cases and boundary cases, such as zero or an empty list, when those inputs are valid.
What does return do inside a function?
Your turn
Write a function that returns the total price for a quantity and a price per item.
def total_price(quantity, price): return quantity * price print(total_price(3, 5)) # 15
BUILT TOGETHER
Help make this explanation better.
Have a clearer explanation, a useful example, or a correction? Share it with the community.
Be the first to add your name when you improve this lesson.
How to get credited