Passing information to functions

Lesson 10 of 54 · Python Foundations

A parameter is a name in a function definition; an argument is a value supplied at a call. Positional arguments match parameters in order.

def remaining(capacity, occupied):
    return capacity - occupied

print(remaining(20, 6))
print(remaining(occupied=6, capacity=20))
14
14

The first call assigns 20 to capacity and 6 to occupied. The second uses keyword arguments: parameter names at the call make the relationship explicit, so their order here does not matter. Passing too few, too many, or conflicting arguments raises TypeError.

A default is used when an argument is omitted:

def fare(stops, price_per_stop=2):
    return stops * price_per_stop

print(fare(3))
print(fare(3, 4))
6
12

price_per_stop receives 2 in the first call and 4 in the second. In this ordinary positional parameter list, required parameters come before parameters with defaults. Defaults are evaluated when the def statement executes, not on every call; mutable defaults require care. Passing None explicitly passes None; it does not select the default.

Chapter index