- Understand the purpose of return statements
- Return single and multiple values from functions
- Understand the difference between print and return
- Use returned values effectively in your code
Return Values
So far, our functions can do things (print messages) and receive input (parameters). But what about giving something back? Imagine asking a calculator to add 5 + 3, but it just displays "Done!" instead of telling you the answer. Pretty useless, right?
Return values are how functions give results back. When a function returns a value, it sends that data back to wherever the function was called. You can then use that value – store it in a variable, use it in another calculation, or pass it to another function.
The Return Statement
The return keyword sends a value back from a function:
How return Works
def add(a, b):
result = a + b
return result ← Send result back to caller
sum = add(5, 3) ← 8 comes back and goes into sum
print(sum) ← 8
The function GIVES BACK a value
The caller RECEIVES that value
Basic Example
def add(a, b):
"""Add two numbers and return the result."""
return a + b
# The returned value can be:
# 1. Stored in a variable
result = add(5, 3)
print(result) # 8
# 2. Used directly
print(add(10, 20)) # 30
# 3. Used in expressions
total = add(5, 3) + add(2, 1)
print(total) # 11
# 4. Passed to another function
double_sum = add(add(1, 2), add(3, 4))
print(double_sum) # 10
print() vs return: The Critical Difference
This is one of the most common confusions for beginners:
print() vs return
print():
• Displays text on the screen
• The value disappears after being shown
• Can't use the value elsewhere
• Good for: showing information to users
return:
• Sends a value back to the caller
• The value can be stored and reused
• Nothing is displayed automatically
• Good for: calculations, data processing
Side by Side Comparison
# Using print (displays but value is lost)
def add_with_print(a, b):
print(a + b) # Shows 8, but returns None
# Using return (value can be reused)
def add_with_return(a, b):
return a + b # Returns 8, shows nothing
# The difference in action:
result1 = add_with_print(5, 3) # Displays: 8
print(f"Result1: {result1}") # Result1: None ← Lost!
result2 = add_with_return(5, 3) # Displays nothing
print(f"Result2: {result2}") # Result2: 8 ← Got it!
# Can you do math with print results?
# total = add_with_print(5, 3) + add_with_print(2, 1)
# TypeError: None + None doesn't work!
# Can you do math with return results?
total = add_with_return(5, 3) + add_with_return(2, 1)
print(total) # 11
Visual Analogy
Real-World Analogy
print() = A loudspeaker
"The answer is 8!"
Everyone hears it, but you can't
catch the sound and use it later
return = A delivery service
Delivers "8" to your hands
Silent, but you now HAVE the value
to do whatever you want with it
Functions Without Return: None
If a function doesn't have a return statement, it returns None:
def greet(name):
print(f"Hello, {name}!")
# No return statement
result = greet("Alice") # Displays: Hello, Alice!
print(result) # None
print(type(result)) # <class 'NoneType'>
Explicit vs Implicit None
# These are all equivalent:
def func1():
print("No return")
# Implicit return None
def func2():
print("Return nothing")
return # Explicit return None
def func3():
print("Return None")
return None # Very explicit return None
# All return None
print(func1()) # None
print(func2()) # None
print(func3()) # None
return Exits the Function
Code after a return statement won't execute:
def check_age(age):
if age < 0:
return "Invalid age" # Exits here if age < 0
print("This never runs") # Unreachable code!
if age >= 18:
return "Adult" # Exits here if adult
return "Minor" # Exits here otherwise
print(check_age(-5)) # "Invalid age"
print(check_age(25)) # "Adult"
print(check_age(12)) # "Minor"
Using return for Early Exit
def divide(a, b):
"""Divide a by b, handling division by zero."""
if b == 0:
return "Cannot divide by zero!" # Exit early
return a / b
print(divide(10, 2)) # 5.0
print(divide(10, 0)) # "Cannot divide by zero!"
Returning Multiple Values
Python lets you return multiple values as a tuple:
def get_dimensions():
"""Return width and height."""
width = 1920
height = 1080
return width, height # Returns a tuple (1920, 1080)
# Unpack into separate variables
w, h = get_dimensions()
print(f"Width: {w}, Height: {h}") # Width: 1920, Height: 1080
# Or keep as tuple
dimensions = get_dimensions()
print(dimensions) # (1920, 1080)
print(dimensions[0]) # 1920
Practical Example: Statistics
def analyze_numbers(numbers):
"""Calculate various statistics for a list of numbers."""
if not numbers:
return None, None, None, None
minimum = min(numbers)
maximum = max(numbers)
total = sum(numbers)
average = total / len(numbers)
return minimum, maximum, total, average
# Use with unpacking
data = [23, 45, 12, 67, 34, 89, 56]
min_val, max_val, sum_val, avg_val = analyze_numbers(data)
print(f"Min: {min_val}") # Min: 12
print(f"Max: {max_val}") # Max: 89
print(f"Sum: {sum_val}") # Sum: 326
print(f"Avg: {avg_val:.2f}") # Avg: 46.57
Chaining Function Calls
Since functions return values, you can chain them:
def double(x):
return x * 2
def add_ten(x):
return x + 10
def square(x):
return x ** 2
# Chain functions together
result = square(add_ten(double(5)))
# Step by step:
# double(5) = 10
# add_ten(10) = 20
# square(20) = 400
print(result) # 400
Practical Examples
Example 1: Temperature Converter
def celsius_to_fahrenheit(celsius):
"""Convert Celsius to Fahrenheit."""
return (celsius * 9/5) + 32
def fahrenheit_to_celsius(fahrenheit):
"""Convert Fahrenheit to Celsius."""
return (fahrenheit - 32) * 5/9
# Use the returned values
temp_c = 25
temp_f = celsius_to_fahrenheit(temp_c)
print(f"{temp_c}°C = {temp_f}°F") # 25°C = 77.0°F
temp_f = 98.6
temp_c = fahrenheit_to_celsius(temp_f)
print(f"{temp_f}°F = {temp_c:.1f}°C") # 98.6°F = 37.0°C
Example 2: Grade Calculator
def calculate_grade(score):
"""Return letter grade and description based on score."""
if score >= 90:
return "A", "Excellent"
elif score >= 80:
return "B", "Good"
elif score >= 70:
return "C", "Satisfactory"
elif score >= 60:
return "D", "Needs Improvement"
else:
return "F", "Failing"
def process_student(name, score):
"""Process a student's grade and create a report."""
grade, description = calculate_grade(score)
passed = score >= 60
return {
"name": name,
"score": score,
"grade": grade,
"description": description,
"passed": passed
}
# Use the returned dictionary
student = process_student("Alice", 85)
print(f"{student['name']}: {student['grade']} ({student['description']})")
# Alice: B (Good)
Example 3: Text Processing
def analyze_text(text):
"""Analyze text and return statistics."""
words = text.split()
word_count = len(words)
char_count = len(text)
char_no_spaces = len(text.replace(" ", ""))
return word_count, char_count, char_no_spaces
def format_text(text, uppercase=False, strip=True):
"""Format text based on options."""
result = text
if strip:
result = result.strip()
if uppercase:
result = result.upper()
return result
# Using the functions
sample = " Hello World Python "
formatted = format_text(sample)
print(f"Formatted: '{formatted}'") # 'Hello World Python'
words, chars, chars_no_space = analyze_text(formatted)
print(f"Words: {words}, Characters: {chars}, No spaces: {chars_no_space}")
# Words: 3, Characters: 18, No spaces: 16
Common Mistakes
1. Forgetting to Use the Return Value
def add(a, b):
return a + b
# WRONG: Calling but not using result
add(5, 3) # Returns 8, but it's lost!
# CORRECT: Store or use the result
result = add(5, 3)
print(add(5, 3))
2. Returning Inside a Loop Too Early
# WRONG: Returns on first iteration!
def find_even(numbers):
for num in numbers:
if num % 2 == 0:
return num # Only finds the FIRST even
return None
# CORRECT: Collect all evens
def find_all_evens(numbers):
evens = []
for num in numbers:
if num % 2 == 0:
evens.append(num)
return evens
3. Printing Instead of Returning
# WRONG: Can't reuse the value
def calculate_tax(amount):
tax = amount * 0.2
print(tax) # Can't use this elsewhere!
# CORRECT: Return for flexibility
def calculate_tax(amount):
return amount * 0.2
# Now you can use it
tax = calculate_tax(100)
total = 100 + tax # Can do math with it!
Key Takeaways
Remember These Points
return sends a value back to the caller
result = function() ← Value goes into result
print ≠ return
print shows, return gives back
No return = returns None
return exits the function immediately
Code after return doesn't run
Return multiple values: return a, b, c
Unpack with: x, y, z = function()
Chain functions: func1(func2(func3(x)))
What's Next?
You now know how functions receive data (parameters) and send data back (return). But what happens to variables inside a function? Can you use a variable defined outside? In the next lesson, we'll explore scope and variable lifetime – understanding where variables live and die.
