Course map
Stage 1: Foundation
Stage 2: Intermediate
Stage 3: Advanced
Stage 4: DSA in Python
Stage 5: Specialization

Part 05 / Topic 8 of 9

Functions as values

In Python a function is a value, like a number. You can store it in a variable or pass it into another function.

Real-world example: apply a chosen price rule to a list of prices.

def festive_offer(price):
    return price * 0.8

def no_offer(price):
    return price

def apply_rule(prices, rule):            # rule is a function
    return [rule(p) for p in prices]

prices = [500, 1200]
print(apply_rule(prices, festive_offer))  # [400.0, 960.0]
print(apply_rule(prices, no_offer))       # [500, 1200]
print(apply_rule(prices, lambda p: p - 50))  # [450, 1150]

Note: we pass festive_offer (no brackets). festive_offer() would call it.

๐Ÿ” Going deeper: a function can also return a function. The inner function remembers variables from the outer one even after the outer one has finished. This is called a closure (see make_counter in examples/03_mutable_default_and_scope.py).

Done here? The practice set for Part 5 โ€” 8 exercises with solutions โ€” is on the part page.

Search the guide