Return Values & Defaults

Send values back with return and give parameters default values.

Syntaxdef 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

Example · python
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 9

When 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.

Example · python
def celsius_to_fahrenheit(c):
    return c * 9 / 5 + 32

temp = celsius_to_fahrenheit(100)
print(temp)   # 212.0

Return multiple values as tuple

Returns two values as an implicit tuple which the caller immediately unpacks.

Example · python
def min_max(numbers):
    return min(numbers), max(numbers)

lo, hi = min_max([4, 1, 9, 2, 7])
print(lo, hi)   # 1 9

Early return to guard input

Uses an early return to exit immediately when the divisor is zero, avoiding ZeroDivisionError.

Example · python
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

  • Be the first to comment on this lesson.