Introduction: Python Return Value in Functions
Some functions perform a calculation or process a value that the rest of the program needs to use. For example, a function that calculates the total cost may need to give that total back so it can be stored, displayed, or used in another calculation.
The Python return statement solves the highlighted issue. Let’s understand how:
1. What Is a Python Return Statement and Return Value?
Python Return Statement: It is a statement that ends a function’s execution and sends a value back to the code that called it. It can return the result of an expression, a variable, or another value.
Python Return Value: It is the value that a function sends back to the code that called it.
Return values are useful when the result of a function needs to be stored, used in a calculation or passed to another function.
Now, let’s look at a simple example to see how a function returns a value and how that value can be used.
def calculate_total(price, quantity):
total = price * quantity
return total
amount = calculate_total(50, 3)
print(amount)
# Output:
150
Explanation: The function calculates the total and uses the return statement (return total) to send the value back to the code that called it. The returned value is then assigned to amount.
2. Returning a Value vs Printing a Value
Returning a value and printing a value are different. The print() function displays a value, while return sends a value back to the code that called the function.
Example
def add_with_return(a, b):
return a + b
def add_with_print(a, b):
print(a + b)
result = add_with_return(10, 5)
print(result)
add_with_print(10, 5)
# Output:
15
15
Explanation: Both functions display 15 in this example, but they work differently. The first function returns 15, so the value can be stored in result and used later. The second function only prints 15; it does not return the value to the calling code.
How to Use Python Return Values
Once a function returns a value, that value can be used in several ways. It can be stored in a variable, used as part of an expression, or passed directly to another function.
Let’s look at each of these uses with simple examples.
- Storing a Return Value
- Using a Return Value in an Expression
- Passing a Return Value to Another Function
1. Storing a Return Value
You can assign a returned value to a variable and use it later in the program.
Example
def calculate_area(length, width):
return length * width
area = calculate_area(10, 5)
print(area)
# Output:
50
Explanation: The function returns 50, and the program stores the value in the area variable. The program can then use the value wherever it needs the area.
2. Using a Return Value in an Expression
You can also use a returned value directly in an expression without first storing it in a separate variable. For example, combine the returned value with another value in a calculation.
Example
def get_price():
return 100
total = get_price() + 20
print(total)
# Output:
120
Explanation: The function returns 100, and the program adds it to 20. The program then assigns the result to total.
3. Passing a Return Value to Another Function
You can also pass a returned value directly to another function as an argument.
Example
def get_number():
return 10
def double(number):
return number * 2
result = double(get_number())
print(result)
# Output:
20
Explanation: The get_number() function returns 10. That returned value is passed directly to double(), which receives it as the number parameter and returns 20.
Functions With and Without Return Values
A function may or may not return a value. Some functions perform an action without returning a value, while others use the Python return statement to return a value that the rest of the program can use.
Let’s look at both types with simple examples.
1. Function Without a Return Value
A function does not need to return a value. It can simply perform an action, such as displaying a message, without sending a value back to the code that called it.
Example
def greet():
print("Hello, Python!")
greet()
# Output:
Hello, Python!
Explanation: The greet() function displays the message but does not return a value to the code that called it.
2. Function With a Return Value
A function can return a value when the calling code needs to use the result produced by the function.
Example
def calculate_square(number):
return number * number
result = calculate_square(5)
print(result)
# Output:
25
Explanation: The calculate_square() function calculates the square of 5 and returns 25. The program stores the returned value in the result variable and then prints it.
What Happens When return Is Used?
When Python reaches a return statement, the function stops running and sends the specified value back to the code that called it. Any statements written after return in the same function do not run.
Let’s see what happens when a function reaches return and what happens when return is used without a value.
1. Return Ends Function Execution
When a function reaches a return statement, Python immediately ends that function’s execution. Any code written after the return statement does not run.
Example
def check_number():
print("Before return")
return 10
print("After return")
result = check_number()
print(result)
# Output:
Before return
10Explanation: The function prints Before return and then reaches return 10. Python ends the function at that point, so the print() statement after return does not run. The function returns 10, which is stored in result.
2. Returning Without a Value
A return statement does not always need to include a value. When a function uses return without a value, Python ends the function and returns None.
Example
def check_number(number):
if number < 0:
return
print("Number is positive")
check_number(-5)
# Output:
Explanation: When the function receives -5, the condition is true, so the return statement ends the function immediately. No value is returned explicitly, so Python returns None.
Examples: Return Values
The following examples show different ways functions can produce Python return values and how those values can be used.
- Example 1: Returning a Calculated Value
- Example 2: Using a Returned Value
- Example 3: Returning Multiple Values
- Example 4: Returning Without a Value
Example 1. Returning a Calculated Value
A function can perform a calculation and return the result to the code that called it.
def calculate_discount(price, discount):
return price * discount / 100
discount_amount = calculate_discount(1000, 10)
print(discount_amount)
# Output:
100.0
Explanation: The parameters price and discount receive the arguments 1000 and 10. The function calculates the discount amount and returns the result, which is stored in discount_amount.
Example 2. Using a Returned Value
A returned value can be stored in a variable and used later in the program.
def calculate_total(price, quantity):
return price * quantity
total = calculate_total(50, 3)
final_amount = total + 20
print(final_amount)
# Output:
170
Explanation: The function returns 150, which is stored in total. The returned value is then used to calculate final_amount.
Example 3. Returning Multiple Values
A function can return more than one value. Python returns them together as a tuple.
def calculate_values(a, b):
total = a + b
difference = a - b
return total, difference
total, difference = calculate_values(10, 4)
print(total)
print(difference)
# Output:
14
6
Explanation: The function returns both total and difference. The returned values are assigned to the two variables on the left side of the assignment.
Example 4. Using a Default Argument With a Return Value
A function can use a default argument and return the calculated result.
def calculate_total(price, quantity=1):
return price * quantity
total1 = calculate_total(100)
total2 = calculate_total(100, 3)
print(total1)
print(total2)
# Output:
100
300
Explanation: In the first call, quantity uses its default value of 1. In the second call, 3 is passed as an argument. Both calls return a calculated total.
Common Mistakes With Python Return Values
Return values are straightforward once the difference between return and print() is clear. However, a few common mistakes can cause unexpected results.
- Using
print()Instead ofreturn - Forgetting to Return a Value
- Writing Code After
return - Using a Returned
NoneValue in a Calculation
1. Using print() Instead of return
Explanation: A common mistake is using print() when the calling code needs to receive the result. Printing displays the value, but it does not send that value back to the caller.
Incorrect Example
def calculate_total(price, quantity):
print(price * quantity)
total = calculate_total(50, 3)
print(total)
# Output:
150
NoneExplanation: The function calculates 50 * 3 and displays 150 using print(). However, print() does not send the value back to the calling code. Therefore, the function returns None, so total receives None.
Correct Example
def calculate_total(price, quantity):
return price * quantity
total = calculate_total(50, 3)
print(total)
# Output:
150Explanation:
- The function calculates
50 * 3and usesreturnto send150back to the calling code. - The returned value is assigned to
total, sototalcontains150. - The
print(total)statement then displays150.
2. Forgetting to Return a Value
A function may calculate a result correctly but still fail to provide that result to the calling code if it does not use return.
Incorrect Example
def calculate_square(number):
result = number * number
square = calculate_square(5)
print(square)
# Output:
NoneExplanation:
- The function calculates
5 * 5and stores the result inresult. - The function does not use
return, so the calculated value is not sent back to the calling code. - Therefore,
calculate_square(5)returnsNone, andsquarereceivesNone.
Correct Example
def calculate_square(number):
result = number * number
return result
square = calculate_square(5)
print(square)
# Output:
25Explanation:
- The function calculates
5 * 5and stores the result inresult. - The
return resultstatement sends25back to the calling code. - The returned value is assigned to
square, sosquarecontains25.
3. Writing Code After return
Once Python executes a return statement, the function ends immediately. Statements placed after that return are not executed.
Incorrect Example
def check_number(number):
if number > 0:
return "Positive"
print("Checking complete")
print(check_number(5))
# Output:
PositiveExplanation:
- The function checks whether
numberis greater than0. - When the condition is true,
return "Positive"executes and immediately ends the function. - The
print("Checking complete")statement comes afterreturn, so it never runs.
Correct Example
def check_number(number):
if number > 0:
print("Checking complete")
return "Positive"
print(check_number(5))
# Output:
Checking complete
PositiveExplanation:
- The function first executes
print("Checking complete")because it appears beforereturn. - The
return "Positive"statement then sends"Positive"back to the calling code and ends the function. - The returned value is passed to
print(), which displaysPositive.
4. Using a Returned None Value in a Calculation
If a function does not return a value, the calling code receives None. Using that None value in a calculation can cause a TypeError.
Incorrect Example
def get_price():
print(100)
price = get_price()
total = price + 20
# Error:
TypeError: unsupported operand type(s) for +: 'NoneType' and 'int'Explanation:
- The function displays
100usingprint(), but it does not return the value. - Therefore,
get_price()returnsNone, sopricecontainsNone. - The expression
price + 20attempts to add an integer toNone, which causes aTypeError.
Correct Example
def get_price():
return 100
price = get_price()
total = price + 20
print(total)
# Output:
120Explanation:
- The function uses
return 100to send100back to the calling code. - The returned value is assigned to
price, sopricecontains100. - The expression
price + 20calculates100 + 20, producing120.
Key Takeaways: Return Values
The main points to remember about Python return values are:
returnsends a value from a function back to the code that called it.- A returned value can be stored, used in an expression, or passed to another function.
print()displays a value but does not return it to the calling code.- A function without an explicit return value returns
None. - A
returnstatement immediately ends the function’s execution. - A function can return multiple values, which Python returns as a tuple.