In Python, the function return value is the key mechanism that allows a function to “output” results. Imagine you define a function to process data (e.g., calculating the sum of two numbers). If you only use print, the result is only displayed on the screen and cannot be used by subsequent code. Return values, however, allow the function to “pass” its internal calculation results to the outside, enabling you to continue processing or store that result.
1. The Simplest Return Value: Using return to Output Results¶
To make a function return a result, use the return statement inside the function. For example, define a function to calculate the sum of two numbers:
def add(a, b):
result = a + b # Calculate the sum of two numbers
return result # Return the result to the outside
# Call the function and capture the return value
sum_result = add(3, 5)
print(sum_result) # Output: 8 (result is stored in sum_result)
Here, return result is the “output” operation of the function. add(3, 5) returns 8, which is assigned to the variable sum_result.
2. Why Use Return Values? Comparing with print¶
Many beginners confuse print and return. print only “displays” the result on the screen, while return allows the result to be used by subsequent code:
# Using print (result cannot be used for further calculations)
def print_sum(a, b):
print(a + b) # Only prints, does not return
print_sum(2, 3) # Output: 5, but the result cannot be stored
# Using return (result can be used for further calculations)
def return_sum(a, b):
return a + b # Return the result
sum_2 = return_sum(2, 3)
sum_3 = return_sum(4, 5)
total = sum_2 + sum_3 # Can continue to calculate
print(total) # Output: 14 (2+3=5, 4+5=9, 5+9=14)
3. What Does a Function Return if There’s No return?¶
If a function has no return statement, Python defaults to returning None (meaning “empty” or “nothing”):
def no_return(a, b):
a + b # Only calculates, no return
result = no_return(1, 2)
print(result) # Output: None (cannot be used for further calculations)
print(result * 3) # Error! Because None cannot be multiplied by 3
Conclusion: To make a function have an “output result”, you must use return to return the desired value.
4. Returning Different Data Types¶
Function return values can be of any type: numbers, strings, lists, dictionaries, etc.
# Return a string
def get_greeting(name):
return f"Hello, {name}!" # Return a string
greet = get_greeting("小明")
print(greet) # Output: Hello, 小明
# Return a list
def get_numbers():
return [1, 3, 5, 7] # Return a list
nums = get_numbers()
print(nums[0]) # Output: 1 (access the first element of the list)
5. Returning Multiple Values (Separated by Commas)¶
Python functions can return multiple values at once (essentially returning a tuple). Use multiple variables to receive the values when calling the function:
def get_user_info():
name = "小红"
age = 20
gender = "女"
return name, age, gender # Return multiple values (tuple)
# Unpack the values into multiple variables
user_name, user_age, user_gender = get_user_info()
print(f"Name: {user_name}, Age: {user_age}, Gender: {user_gender}")
# Output: Name: 小红, Age: 20, Gender: 女
If you only need some values, use _ to ignore the unwanted return values:
name, _, gender = get_user_info() # Ignore the age
print(f"Name: {name}, Gender: {gender}") # Output: Name: 小红, Gender: 女
6. Note: return Immediately Stops the Function¶
Once a function executes a return, any subsequent code will not run:
def early_return():
return "This is the first return value"
print("This line will never execute!") # Function stops after return
print(early_return()) # Output: This is the first return value
Practice Exercise¶
Try writing a function calculate_stats(numbers) that takes a list numbers and returns the “average” and “maximum” of the list. Call the function and print the results.
Hint: Use sum() to calculate the total, max() to get the maximum value, and return both values with return.
Summary: Function return values are implemented using return, enabling functions to provide results for subsequent code. return can return any type (including multiple values), and functions without return default to returning None. Mastering return values is a fundamental Python skill that makes your code more flexible!