Table of Contents
Why Return Values Matter
When you call a function, it can do two main things:
- Perform some actions (print text, write to a file, etc.).
- Give back a result that you can use later in your code.
That “giving back a result” is called returning a value.
A function’s return value is what you get back when you call it, and you can store it in a variable, use it in a calculation, or pass it to another function.
Many built‑in functions you already know use return values:
len("hello")returns5int("42")returns42max(3, 10, 7)returns10
The `return` Statement
Inside a function, you use the return keyword to send a value back to the caller.
Basic pattern:
def function_name():
# do some work
return something # send 'something' backExample:
def add(a, b):
result = a + b
return result
sum_of_numbers = add(3, 5) # sum_of_numbers will be 8
print(sum_of_numbers)
Key idea: return passes a value out of the function to wherever the function was called.
You can also return an expression directly:
def add(a, b):
return a + bUsing Return Values vs. Printing
New programmers often confuse returning with printing.
print()shows something on the screen.returnsends a value back from a function so your program can use it.
Compare:
def add_and_print(a, b):
result = a + b
print(result) # only shows it, does NOT return
def add_and_return(a, b):
return a + b # returns the sum
# Using the first function:
x = add_and_print(2, 3)
print("x is:", x)Output:
5
x is: NoneExplanation:
add_and_print(2, 3)prints5, but doesn’t return anything.- In Python, a function that doesn’t return a value automatically returns
None. - So
xbecomesNone.
With add_and_return:
y = add_and_return(2, 3)
print("y is:", y)Output:
y is: 5
Use printing for user messages, debugging, and results you want to see.
Use return values for data you want to reuse and combine in your program.
Functions That Return Nothing: `None`
If a function has no return statement, or has a return with no value, Python returns None.
def say_hello(name):
print("Hello,", name)
result = say_hello("Alice")
print("result is:", result)Output:
Hello, Alice
result is: NoneYou can also write:
def do_nothing():
return # no value
value = do_nothing()
print(value) # None
None is a special value in Python that means “nothing” or “no value”.
Functions that are meant to perform an action (like printing, writing to a file, etc.) often return None.
Functions that are meant to calculate something should usually return a meaningful value instead.
Returning Different Types of Values
A function can return any type of value: numbers, strings, booleans, lists, dictionaries, and more.
Returning a number
def area_of_rectangle(width, height):
return width * height
area = area_of_rectangle(4, 3)
print(area) # 12Returning a string
def greeting(name):
return "Hello, " + name + "!"
msg = greeting("Sam")
print(msg) # Hello, Sam!Returning a boolean
def is_even(n):
return n % 2 == 0
print(is_even(4)) # True
print(is_even(7)) # FalseReturning a list or other collections
def first_and_last(text):
return [text[0], text[-1]]
result = first_and_last("Python")
print(result) # ['P', 'n']Returning Multiple Values
Python functions can only return one object, but that object can be a tuple (or list, etc.) that contains multiple pieces of data. This is often written as if returning “multiple values”.
def divide_and_remainder(a, b):
quotient = a // b
remainder = a % b
return quotient, remainder # returns a tuple: (quotient, remainder)
q, r = divide_and_remainder(17, 5)
print("Quotient:", q) # 3
print("Remainder:", r) # 2
Here, divide_and_remainder(17, 5) returns the tuple (3, 2), and Python unpacks it into q and r.
You can also capture the tuple directly:
result = divide_and_remainder(17, 5)
print(result) # (3, 2)
print(result[0]) # 3
print(result[1]) # 2How `return` Ends a Function Early
As soon as Python reaches a return statement inside a function, it:
- Evaluates the value (if any) after
return. - Immediately exits the function.
- Sends that value back to the caller.
Any code after return in the same block will not run.
def test_return():
print("Before return")
return 42
print("After return") # this line never runs
value = test_return()
print("Returned:", value)Output:
Before return
Returned: 42You can use this behavior to exit a function early in certain situations.
Example: validating input
def safe_divide(a, b):
if b == 0:
print("Cannot divide by zero.")
return None # exit early with a special value
return a / b
print(safe_divide(10, 0)) # message + None
print(safe_divide(10, 2)) # 5.0Designing Functions With Useful Return Values
When writing a function, a good question to ask:
“What should this function give back?”
Some common patterns:
Compute and return a result
def average(a, b, c):
return (a + b + c) / 3
avg = average(10, 20, 30)
print(avg) # 20.0Return a “success or failure” flag
def is_valid_age(age):
return age >= 0 and age <= 120
print(is_valid_age(25)) # True
print(is_valid_age(-1)) # FalseReturn data instead of printing it
Instead of:
def make_full_name(first, last):
print(first + " " + last)Prefer:
def make_full_name(first, last):
return first + " " + last
full = make_full_name("Ada", "Lovelace")
print("Full name:", full)Returning data makes your function more flexible: you can print it, store it, compare it, or send it somewhere else.
Common Mistakes With Return Values
1. Forgetting to return
def add(a, b):
result = a + b # computed, but never returned
sum_value = add(2, 3)
print(sum_value) # NoneFix:
def add(a, b):
result = a + b
return result2. Thinking `print` is the same as `return`
def square(n):
print(n * n) # only displays it
result = square(4)
print("result:", result) # result: NoneFix:
def square(n):
return n * n3. Code after `return` expecting to run
def example():
return 10
print("This will never happen")
Anything after return in the same block is unreachable and should be removed or moved before return.
Simple Practice Ideas
Here are some small function ideas you can try to practice return values:
fahrenheit_to_celsius(f)
Return the Celsius temperature.full_name(first, last)
Return a combined"First Last"string.is_adult(age)
ReturnTrueif age is at least 18, otherwiseFalse.min_max(a, b, c)
Return both the smallest and largest of three numbers (for example as a tuple(min_value, max_value)).count_char(text, char)
Return how many times a character appears in a string.
Focus on:
- Using
returninstead ofprintwhen you want to use the result. - Choosing clear and useful values to return.