Returning Values
So far, our functions have performed actions like printing messages. But functions can also produce values — calculating results and sending them back to the code that called them. This is done with the return statement.
The Return Statement
return sends a value back to wherever the function was called:
def add(a, b):
return a + b
result = add(3, 5)
print(result) # 8
When Python executes return a + b, it calculates 3 + 5, then sends 8 back. The calling code captures this value in the variable result.
Using Returned Values
Returned values can be used anywhere you'd use a regular value:
def add(a, b):
return a + b
# Store in a variable
total = add(10, 20)
# Use directly in expressions
grand_total = add(10, 20) + add(5, 5)
print(grand_total) # 40
# Pass to another function
print(add(100, 200)) # 300
# Use in conditions
if add(2, 2) == 4:
print("Math works!")
This flexibility is what makes returning values so powerful.
Return Exits the Function
When Python hits a return statement, the function immediately stops — any code after return won't run:
def check_positive(number):
if number > 0:
return "positive"
if number < 0:
return "negative"
return "zero"
print(check_positive(5)) # positive
print(check_positive(-3)) # negative
print(check_positive(0)) # zero
Each return exits the function, so only one runs per call.
Functions Without Return
If a function doesn't have a return statement (or reaches the end without returning), it returns None — Python's way of saying "no value":
def greet(name):
print(f"Hello, {name}!")
# No return statement
result = greet("Alice") # Prints: Hello, Alice!
print(result) # None
This is fine for functions that perform actions rather than calculate values.
A Practical Example
def calculate_tax(amount, rate=0.08):
return amount * rate
def calculate_total(price, quantity, tax_rate=0.08):
subtotal = price * quantity
tax = calculate_tax(subtotal, tax_rate)
return subtotal + tax
# Now we can use the result
total = calculate_total(29.99, 3)
print(f"Your total is ${total:.2f}")
# Or compare totals
if calculate_total(50, 2) > 100:
print("Order qualifies for free shipping!")
Functions that return values can be combined and composed, building complex behavior from simple pieces.