Python Scope Examples
Short, runnable programs that show python variable scope in action. Read the explanation, press Run, then change the code and try your own ideas. New to the topic? Start with the Python Variable Scope lesson.
1Every call starts with fresh local variables
counter is created again on each call and thrown away afterwards, so it never gets past 1. To remember something between calls, keep it outside the function and pass it in, or return it.
def count_up():
counter = 0
counter += 1
return counter
print(count_up())
print(count_up())
print(count_up())Expected output1
1
1
2Reading a global works, assigning creates a local
check() only reads limit, so it sees the global. change_limit() assigns to limit, which creates a brand-new local variable and leaves the global untouched.
limit = 100
def check(amount):
return amount <= limit
def change_limit(new):
limit = new
print("inside:", limit)
change_limit(500)
print("outside:", limit)
print(check(250))Expected outputinside: 500
outside: 100
False
3Enclosing scope and nonlocal
increment() is defined inside make_counter(), so it can see count in the enclosing scope. nonlocal lets it change that variable, which keeps its value between calls.
def make_counter():
count = 0
def increment():
nonlocal count
count += 1
return count
return increment
clicks = make_counter()
clicks()
clicks()
print("Clicks:", clicks())Expected outputClicks: 3
4Parameters are local variables too
The parameter salary is a separate local name. Giving it a new value inside the function doesn't change the global salary.
def apply_bonus(salary):
salary = salary * 1.1
return round(salary, 2)
salary = 50000
new_salary = apply_bonus(salary)
print("Before:", salary)
print("After:", new_salary)Expected outputBefore: 50000
After: 55000.0
Practise next
Python Variable Scope exercises → Back to the lesson
Python Functions examplesPython Closures examplesPython Modules and Imports examplesPython Exceptions: try, except, else and finally examples