Python Scope
Scope is the part of a program where a name can be used. Where a variable is created decides where it can be used.
A local variable
message is created inside show(). It lives only inside that function.
def show():
message = "inside"
print(message)
show()Reading a global variable
city is created outside the function. The function can read it freely.
city = "Paris"
def show_city():
print(city)
show_city()The same name, two variables
The x inside change() is a new local variable. The outer x stays untouched.
x = "outer"
def change():
x = "inner"
print(x)
change()
print(x)The common mistake
This function tries to change the global count. Without the word global, Python treats count as local, and this fails.
count = 0
def bump():
count = count + 1
print(count)
bump()Example
count = 0
def bump():
global count
count = count + 1
print(count)
bump()
bump()
print(count)Key points
- Scope: the part of a program where a name can be used
- Local variable: a variable created inside a function.
- It lives only in that function.
- Global variable: a variable created outside all functions.
- Every function can read it.
- Use the global keyword inside a function to change a global variable
- The same name in two places can be two different variables
- Python looks names up in LEGB order: Local, Enclosing, Global, then Built-in
In this example, count starts at 0 outside the function. Inside bump(), the line global count says this name means the global one. The function adds 1 and prints the new value. The first call prints 1, and the second call prints 2. The last print runs outside the function. It also shows 2, so the global variable really changed.
Note
A local variable with the same name as a global one shadows it.
Shadow means the local name hides the global one inside that function.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Python Playground
Exercise
What must a function use to change a global variable?