Chapter 6: Function scope

Local scope

face Josiah Wang

There is one important point you should note about functions.

Any variable and parameter you create inside a function definition is local.

This means that the variables (including the parameters) CANNOT be seen or used outside the function definition.

What is said in this room stays in this room

Sort of how nobody else can see or use your heart and intestines. Only your body can use it. It is all private (at least as long as nobody rips them out!)

Try running the code below.

1
2
3
4
5
6
7
8
def absolute_value(number):
    threshold = 0
    if number < threshold:
        return -number
    return number

result = absolute_value(5)
print(number)

You will get a NameError. Python tells you that name ‘number’ is not defined (on Line 8). Because it is not defined! Only absolute_value() has its own local variable called number that nobody else can access.