Decisions inside functions

Lesson 27 of 54 · Python Foundations

A function can return a result as soon as a condition decides it. return exits the whole function, not just the if block. Without it, execution continues after the block.

def delivery_status(weight):
    if weight < 0:
        return "invalid weight"
    if weight <= 5:
        return "standard"
    return "heavy"

print(delivery_status(-1))
print(delivery_status(5))
print(delivery_status(6))
invalid weight
standard
heavy

The first condition rejects an invalid input early. When the input is 5, that condition is false, the next is true, and the function exits with "standard". The final return handles valid weights above five. This avoids nesting a second if inside an else.

A function can also return a comparison directly when its result is already the desired Boolean:

def within_limit(size, limit):
    return size <= limit

print(within_limit(12, 12))
print(within_limit(13, 12))
True
False

If no return is reached, Python returns None. Place shared work after a conditional only when it really should happen on every path that reaches it. For instance, code after an early return does not run for that call.

Chapter index