In Python, a function can return a value to the caller using the return statement. Returning a value means passing the result of the function’s computation back to the place where the function was called.
1.) Using return Statement:
- The return statement ends the function’s execution and sends back a value (or values) to the caller.
Example – Returning a Single Value:
def add(a, b):
return a + b
result = add(3, 4)
print(result) # Output: 7Explanation:
- The function add() takes two arguments and returns their sum.
- The return statement gives back the result, which is stored in the variable result.
2.) Returning Multiple Values:
- Python functions can return multiple values by separating them with commas. Internally, these values are returned as a tuple.
Example – Returning Multiple Values:
def operations(x, y):
return x + y, x - y, x * y
sum_, diff, prod = operations(10, 5)
print(sum_, diff, prod) # Output: 15 5 50Explanation:
- The function operations() performs three arithmetic operations and returns all three results at once.
- The values returned are unpacked into three separate variables: sum_, diff, and prod.
Discussion 0