In Python, the return
Purpose of the return statement
The returnreturn
Any code after the return
Example: Simple return
def add(a, b):
result = a + b # Calculate the sum
return result # Return the result to the caller
sum_value = add(3, 5) # Calling the function and storing the result
print("The sum is:", sum_value) # Output: The sum is: 8
Explanation:
- The
function takes two parameters,add(a, b) anda .b - It calculates their sum and uses the
statement to send this result back to the caller.return - The returned value is stored in
, which is then printed.sum_value
Returning multiple values
Python allows functions to return multiple values at once using tuples. This is useful when you want to send back more than one result.
Example: Returning multiple values
def arithmetic_operations(x, y):
addition = x + y
subtraction = x - y
return addition, subtraction # Returning both values as a tuple
result_sum, result_difference = arithmetic_operations(10, 4) # Unpacking the returned tuple
print("Sum:", result_sum) # Output: Sum: 14
print("Difference:", result_difference) # Output: Difference: 6
Explanation:
- The function
calculates both the sum and the difference ofarithmetic_operations(x, y) andx .y - It returns these two values as a tuple.
- The caller unpacks the tuple into two variables,
andresult_sum , and prints them.result_difference
Implicit return
If a function does not include a returnNone. This behavior can be useful when you want to create a function that only performs an action without returning a value.
Example: Implicit return
def no_return():
print("This function has no return statement.")
result = no_return() # Calling the function
print(result) # Output: None
Explanation:
- The function
prints a message but does not have ano_return() statement.return - By default, it returns
, which is captured by the variableNone .result
Return vs. Print
While the print()returnprint()return
Example: Return vs Print
def double(x):
print("Doubling:", x * 2) # Prints the doubled value
return x * 2 # Returns the doubled value
result = double(5)
print("Returned value:", result) # Output: Returned value: 10
Explanation:
- The function
both prints the doubled value and returns it.double(x) - The
value is stored inreturn , while theresult statement shows the value during the function's execution.print
Summary
The return
- Single Return Value: A function can return a single value, such as the result of a calculation.
- Multiple Return Values: A function can return multiple values as a tuple.
- Implicit Return: If no
statement is provided, Python returnsreturn by default.None - Difference with
: Theprint() statement provides values for further use, whilereturn is used for displaying information.print()
