The return
keyword in Python is used in functions to send a result (or value) back to the caller. It terminates the function’s execution and specifies the value that should be returned to the calling code.
Example
def add_numbers(a, b):
return a + b
result = add_numbers(3, 5)
print(result)
Output:
8
Syntax
return [expression]
expression
: Optional. If provided, this value is returned to the caller. If omitted, None is returned by default.
Why Use return?
- Output Values: To send results from a function back to the caller for further use.
- Stop Function Execution: Terminate the function’s execution once the return statement is encountered.
- Reuse Logic: Allows the same function to be used in different parts of the code with varying inputs and outputs.
Common Examples
1. Returning a Single Value
def square(number):
return number ** 2
print(square(4)) # Output: 16
2. Returning Multiple Values
def get_coordinates():
x = 10
y = 20
return x, y # Returning multiple values as a tuple
coords = get_coordinates()
print(coords) # Output: (10, 20)
3. Using return to Terminate a Function
def check_even(number):
if number % 2 == 0:
return True
return False
print(check_even(4)) # Output: True
print(check_even(5)) # Output: False
4. Using return with Conditional Logic
def grade(score):
if score >= 90:
return "A"
elif score >= 75:
return "B"
else:
return "C"
print(grade(85)) # Output: B
5. Default Return Value
If no return statement is provided, the function returns None
.
def no_return():
pass
result = no_return()
print(result) # Output: None