Return Values & Defaults
Send values back with return and give parameters default values.
Syntax
def greet(name='Guest'):
return ...The return statement sends a value back to the caller and ends the function immediately.
Default parameters
Give a parameter a default with =. It is used when no argument is passed. Parameters with defaults must come after those without.
Returning several values
Return several values separated by commas and Python packs them into a tuple, which you can unpack.
Example
def greet(name='Guest'):
return f'Welcome, {name}'
print(greet('Ada'))
print(greet())
def min_max(nums):
return min(nums), max(nums)
low, high = min_max([3, 9, 1])
print(low, high)
# Output:
# Welcome, Ada
# Welcome, Guest
# 1 9When to use it
- A tax calculator returns the computed amount so the caller can add it to the subtotal.
- A validation function returns True or False so the caller decides whether to proceed.
- A parser returns a tuple of (status, data) so the caller can unpack both pieces of information.
More examples
Return a single value
Returns a computed float that the caller stores in a variable for further use.
def celsius_to_fahrenheit(c):
return c * 9 / 5 + 32
temp = celsius_to_fahrenheit(100)
print(temp) # 212.0Return multiple values as tuple
Returns two values as an implicit tuple which the caller immediately unpacks.
def min_max(numbers):
return min(numbers), max(numbers)
lo, hi = min_max([4, 1, 9, 2, 7])
print(lo, hi) # 1 9Early return to guard input
Uses an early return to exit immediately when the divisor is zero, avoiding ZeroDivisionError.
def safe_divide(a, b):
if b == 0:
return None # early return on bad input
return a / b
print(safe_divide(10, 2)) # 5.0
print(safe_divide(10, 0)) # None
Discussion