Beginner-Friendly Topic
Take your time - it's perfectly normal to re-read this topic 2-3 times. Try the interactive code editor below to run code yourself. Use the Q&A section to check your understanding before moving on. You've got this! 🚀
Return Values
The return statement sends a value back from a function to the caller. Functions without return implicitly return None. You can return any data type, including multiple values.
Return Values
# Returning a value
def add(a, b):
return a + b
result = add(5, 3)
print(result) # 8
# Using returned value directly
print(add(10, 20)) # 30
# Return multiple values (as tuple)
def min_max(numbers):
return min(numbers), max(numbers)
low, high = min_max([5, 2, 8, 1, 9])
print(f"Min: {low}, Max: {high}")
# Early return
def check_age(age):
if age < 0:
return "Invalid age"
if age >= 18:
return "Adult"
return "Minor"
print(check_age(25)) # Adult
print(check_age(10)) # Minor
print(check_age(-5)) # Invalid age
# No return = returns None
def say_hello():
print("Hello!")
result = say_hello()
print(result) # NoneTip
Tip
Return multiple values as a tuple: return min_val, max_val. Then unpack: low, high = min_max(data). Very Pythonic and clean.
Functions are first-class objects in Python - pass them, return them, store them
Common Mistake
Warning
Using print() inside a function when you should use return. print() displays output but doesn't give you a value to use. return lets you store and reuse the result.
Practice Task
Note
(1) Write a function that returns both min and max of a list. (2) Write one with early return for invalid input. (3) Check what happens when there's no return.