Python Return Values: How Functions Send Data Back
A Python function returns a value by using the return statement. That value is sent back to the code that called the function, where it can be stored, used in an expression, or passed to another function. This article shows how return values work, how Python handles multiple values, and the mistakes that lead to None or unpacking errors.
Difficulty: Beginner
Helpful to know first: basic Python syntax, variables, and how to define and call a function.
How Python Return Values Work
A return value is the result a function gives back after it finishes running. When Python reaches return, the function stops immediately and sends the value after it back to the caller.
If a function does not contain a return statement, Python returns None automatically. That is why functions used for printing or logging are different from functions used to compute a result.
Here is the smallest useful example:
def add(a, b):
return a + b
result = add(2, 3)
print(result) # Output: 5The function calculates a + b and returns the sum. The caller stores that value in result and prints it.
Think of return as the function handing a value back to the line that called it.
Common Ways to Use Return Values
Storing the result in a variable
The most common use is to save the returned value and use it later.
def square(n):
return n * n
value = square(4)
print(value) # Output: 16The function does not print anything itself. It returns a number, and the caller decides what to do with it.
Using the return value inside another expression
Return values are useful because they can be combined with other calculations.
def double(n):
return n * 2
print(double(5) + 1) # Output: 11Python first evaluates double(5), gets 10, and then adds 1.
Returning a value from a decision
A function can return different values depending on a condition.
def is_even(n):
if n % 2 == 0:
return True
return False
print(is_even(8)) # Output: True
print(is_even(7)) # Output: FalseThis pattern is common when a function checks something and returns a result that the caller can test later.
Returning data instead of printing it
A function that returns data is more flexible than one that only prints. The caller can print it, save it, compare it, or reuse it.
def build_message(name):
return f"Hello, {name}!"
message = build_message("Ada")
print(message) # Output: Hello, Ada!If the function had printed directly, you could not easily reuse the text elsewhere.
What Happens When a Function Returns Nothing
If a function reaches the end without a return, Python returns None. This is not an error. It is the built-in value that means “nothing useful was returned.”
def greet(name):
print(f"Hello, {name}!")
result = greet("Maya")
print(result) # Output:
# Hello, Maya!
# NoneThe function prints a greeting, then returns None because there is no explicit return value. This is a common source of confusion for beginners.
A function can print text and still return None. Printing and returning are different actions.
How Python Handles Multiple Return Values
Python does not truly return several separate values at once. Instead, it returns one object, often a tuple, and the caller can unpack it into multiple variables.
def min_max(numbers):
return min(numbers), max(numbers)
smallest, largest = min_max([3, 8, 1, 6])
print(smallest, largest) # Output: 1 8The comma creates a tuple. Python then unpacks that tuple into smallest and largest.
You can also keep the tuple as one value:
pair = min_max([3, 8, 1, 6])
print(pair) # Output: (1, 8)That is useful when you want to pass the whole result around before unpacking it.
How Return Values Behave in Detail
return stops the function immediately
Anything after return in the same path is skipped. This matters when you have checks or cleanup code.
def check_number(n):
if n < 0:
return "negative"
return "non-negative"
print(check_number(-3)) # Output: negativeThe first matching return ends the function right away.
Every path should return the same kind of value
Functions are easier to use when they return the same type or shape of result every time. Mixing int, str, and None in one function makes the caller harder to write.
def find_name(names, target):
for name in names:
if name == target:
return name
return NoneThis version is clear because it either returns the matching name or returns None when nothing is found.
Objects are returned by reference, not copied
When a function returns a list, dictionary, or other mutable object, the caller receives a reference to that same object. If you change it later, the original object changes too.
def make_list():
return [1, 2, 3]
numbers = make_list()
numbers.append(4)
print(numbers) # Output: [1, 2, 3, 4]This is the normal Python object model. A return value does not create a hidden copy unless your code explicitly makes one.
Return values do not print by themselves
Python gives the value back to the caller, but nothing appears on the screen unless you print it or use it in some other visible way.
def area(width, height):
return width * height
area(3, 5)
print("done") # Output: doneThe call to area happens, but the returned value is ignored.
Predict the Output
Snippet 1: Returning before the last line
def score(points):
if points > 10:
return "high"
return "low"
print(score(12))What does this print?
Show answer
It prints high.
Python checks points > 10. That condition is true for 12, so the first return runs and the function ends immediately. The final return is skipped.
# Output: highSnippet 2: A function call with no explicit return
def shout(text):
print(text.upper())
print(shout("hello"))What happens?
Show answer
It prints two lines:
# Output:
# HELLO
# NoneThe function shout prints HELLO, but it does not return a value. Python therefore returns None, and the outer print() prints that None value on the second line.
Common Mistakes with Python Return Values
Using print when you need return
Beginners often print a result inside a function and then expect the caller to receive it. Printing shows text on the screen, but it does not send a value back.
Problem: The function looks like it produces a result, but it returns None, so later code cannot use the value.
def add(a, b):
print(a + b)
total = add(2, 3)
print(total)Fix: Return the value, then print it outside the function if needed.
def add(a, b):
return a + b
total = add(2, 3)
print(total)The corrected version works because the function now sends the sum back to the caller.
Forgetting that a missing return gives None
If a function has a path with no return, Python gives back None on that path.
Problem: Some inputs produce a string, but other inputs fall off the end of the function and return None, which breaks later string operations.
def get_label(value):
if value > 0:
return "positive"
print(get_label(-1))Fix: Return a value for every path you care about.
def get_label(value):
if value > 0:
return "positive"
return "not positive"The fixed function always returns a string, so callers can use it safely.
Trying to unpack too few or too many return values
When a function returns one object, the caller must unpack the right number of items. A mismatch raises an error.
Problem: The caller expects two values, but the function returns only one string.
def get_name():
return "Ada"
first, last = get_name()Fix: Return the shape of data the caller expects, or unpack only one value.
def get_name():
return "Ada"
name = get_name()
print(name)This works because the assignment matches the single returned value.
Returning from the wrong indentation level
A return inside a loop ends the whole function, not just the current loop iteration.
Problem: The function stops on the first item, so later items are never checked.
def first_even(numbers):
for number in numbers:
if number % 2 == 0:
return number
return NoneFix: Use continue when you want to skip one item, and use return only when you are ready to end the function.
def first_even(numbers):
for number in numbers:
if number % 2 == 0:
return number
return NoneThe corrected version keeps checking until it finds the first even number or reaches the end.
Find the Bug
Here is a function that tries to return the average of a list. It looks reasonable, but it has a subtle bug related to return values. Find it before opening the answer.
def average(numbers):
total = 0
for number in numbers:
total += number
return total / len(numbers)
print(average([2, 4, 6]))Show answer
The bug is the indentation of return. It is inside the loop, so the function returns after processing the first number only.
That means the function calculates 2 / 3 and stops. The rest of the list is ignored.
Fixed code:
def average(numbers):
total = 0
for number in numbers:
total += number
return total / len(numbers)
print(average([2, 4, 6])) # Output: 4.0The fixed version works because it waits until the loop finishes before returning the final average.
When to Return a Value and When to Use Something Else
Most functions should either return a value, perform an action, or clearly do both. The important question is what the caller needs afterward.
| Use return value when... | Use printing or side effects when... |
|---|---|
| You need the result in later code. | You only want to show information to the user. |
| The caller may store, compare, or reuse the result. | The work is complete once the output is shown or saved. |
| You want the function to be easy to test. | The function is mainly about interaction, logging, or output. |
A good pattern is to separate computing from displaying. For example, one function can calculate a price, and another part of the program can print it.
def subtotal(items):
return sum(items)
total = subtotal([12, 8, 5])
print(f"Total: {total}") # Output: Total: 25This makes the function reusable in more than one place.
Interview Questions About Python Return Values
What is the difference between return and print?
print writes text to the screen. return sends a value back to the caller. A function can do both, but they serve different purposes.
What does a function return if there is no return statement?
It returns None. That happens automatically when execution reaches the end of the function.
How can a Python function return two values?
It returns one object, usually a tuple, and the caller unpacks it into two variables. The syntax uses a comma in the return statement and a matching number of variables on the left side.
Try It Yourself
Write a function named temperature_report that:
- takes one number, celsius
- returns a tuple containing the Celsius value and the Fahrenheit value
- prints the returned tuple for 25 degrees Celsius
Expected output:
(25, 77.0)Hint: Use the formula fahrenheit = celsius * 9 / 5 + 32 and return both values separated by a comma.
Show solution
def temperature_report(celsius):
fahrenheit = celsius * 9 / 5 + 32
return celsius, fahrenheit
print(temperature_report(25)) # Output: (25, 77.0)Summary
- A Python function sends data back with return.
- return ends the function immediately.
- If a function has no explicit return, Python returns None.
- Multiple return values are usually returned as a tuple and unpacked by the caller.
- Returned mutable objects are not copied automatically.
- Use return when the caller needs the result, and use print only when you want visible output.
Next, read about Python function arguments to see how input values reach a function before it returns a result.