return statement in Python
What is the return Statement? The return statement is used inside a function to send a value back to the place where the function was called.
When Python executes a return statement:
• It exits the function immediately.
• It returns the specified value (if any) to the caller.
Syntax
def function_name(parameters):
# function body
return expression • expression → the value or result that we want the function to give back.
• If there is no return, the function automatically returns None.
The return statement cannot be used outside of the function.
Example: Returning a Single Value
Python
# Function definition
def add_numbers(a, b):
result = a + b
return result # returning the result to the caller
# Function call
sum_value = add_numbers(10, 5)
print("Sum is:", sum_value) Output: Sum is: 15
Explanation: • When return result executes, the function ends and gives back 15 to the variable sum_value.
Example: Function Without return.
Python
def greet(name):
print("Hello", name)
result = greet("Ashish")
print(result) Output: Hello Ashish
None
Explanation: • Since there’s no return, Python automatically returns None.
Example: Returning Multiple Values. We can return multiple values separated by commas — Python automatically packs them into a tuple.
Python
def calculate(a, b):
sum_ = a + b
diff = a - b
return sum_, diff # returning two values
# Function call
result = calculate(10, 5)
print(result) # Output: (15, 5)
# You can also unpack the values
sum_value, difference = calculate(10, 5)
print("Sum:", sum_value)
print("Difference:", difference) Output: (15, 5)
Sum: 15
Difference: 5
Example: Using return to Exit a Function Early We can use return to stop execution before reaching the end of a function.
Python
def divide(a, b):
if b == 0:
return "Cannot divide by zero!" # early return
return a / b
print(divide(10, 2)) # Output: 5.0
print(divide(10, 0)) # Output: Cannot divide by zero! Key Points to Remember
- You can have multiple return statements, but only one is executed per call.
- When a return executes, the function stops immediately.
- A function that doesn’t explicitly return something gives None.
- You can return any data type: number, string, list, tuple, dictionary, even another function.