How to Check If a Function Returns a Specific Value in Python
In Python, functions are designed to perform tasks and often send data back to the main program using the return statement. Verifying that a function returns the expected value is a fundamental part of logic control, bug fixing, and automated testing.
This guide explains how to capture function outputs, compare them against expected values using conditional logic, and handle common pitfalls like implicit None returns.
Understanding Function Returns
When a function executes a return statement, it immediately exits and passes a value back to the line of code that called it. To check this value, you must capture it in a variable.
def calculate_sum(x, y):
"""Calculates sum and returns the result."""
return x + y
# 1. Call the function
# 2. Capture the return value in 'result'
result = calculate_sum(10, 5)
print(f"Returned value: {result}")
Output:
Returned value: 15
Method 1: Using Conditional Logic (if-else)
The most common way to check a return value during runtime is to compare the captured variable against an expected value using standard comparison operators (==, !=, >, etc.).
Checking Exact Matches
This is useful when a function has conditional logic that might return different results based on inputs.
def conditional_math(x, y):
"""
Returns the sum.
However, if the sum is greater than 10, it returns double the sum.
"""
total = x + y
if total > 10:
return total * 2
return total
# Case A: Sum is 5 (<= 10), so returns 5
val_a = conditional_math(2, 3)
# Case B: Sum is 15 (> 10), so returns 30
val_b = conditional_math(10, 5)
# ✅ Logic Check
if val_b == 30:
print(f"Success: Function returned 30 as expected.")
else:
print(f"Failure: Expected 30, got {val_b}")
Output:
Success: Function returned 30 as expected.
When checking return values, ensure you compare matching data types. A return value of string "5" is not equal to integer 5.
Method 2: Using Assertions (Debugging)
For testing and debugging, you can use the assert keyword. This checks if a condition is True; if it is False, the program crashes with an AssertionError. This is the precursor to writing unit tests.
def get_status_code():
return 200
# ✅ Correct: The condition is True, code continues
assert get_status_code() == 200
print("First assertion passed.")
try:
# ⛔️ Incorrect: Expecting 404, but got 200
assert get_status_code() == 404
except AssertionError:
print("Second assertion failed: Value was not 404.")
Output:
First assertion passed.
Second assertion failed: Value was not 404.
Common Pitfall: Printing vs. Returning
A frequent error involves functions that print() a value instead of return-ing it. In Python, a function without a return statement implicitly returns None.
The "None" Trap
def fake_calculator(a, b):
# ⛔️ Incorrect: This prints to console but returns None
print(a + b)
# We expect 'result' to be 10, but it is actually None
result = fake_calculator(5, 5)
print(f"Captured value: {result}")
if result == 10:
print("This will NOT print.")
else:
print("Check failed: result is not 10.")
Output:
10
Captured value: None
Check failed: result is not 10.
The Fix
Replace print with return to pass the data back to the program.
def real_calculator(a, b):
# ✅ Correct: Returns the value
return a + b
result = real_calculator(5, 5)
if result == 10:
print("Check passed: Result is 10.")
Output:
Check passed: Result is 10.
If you see None when checking a function's output, explicitly check if you forgot the return statement in your function definition.
Conclusion
To successfully check if a function returns a specific value:
- Capture the output: Assign the function call to a variable (e.g.,
result = func()). - Verify the logic: Ensure the function uses
return, notprint. - Compare: Use
if result == expected_value:for runtime logic orassert result == expected_valuefor testing.