Names inside a call

Lesson 13 of 54 · Python Foundations

Scope describes where a name can be looked up in code. Parameters and names assigned inside a function are normally local to each call.

def package_weight(box, contents):
    total = box + contents
    return total

weight = package_weight(2, 5)
print(weight)
7

During the call, box is 2, contents is 5, and total is 7. The value is returned and bound to weight outside the function. The name total itself is not made available outside: print(total) after this example raises NameError if no outer total exists.

call: box → 2, contents → 5, total → 7
                                  return → weight outside

Each call has its own local bindings. Returning a value lets the caller use it without needing access to the local name.

Chapter index