Variable scope
Scope is where in your program a name can be seen. Variables created inside a function are different from those created outside it.
Local variables
A variable created inside a function is local: it exists only while the function runs, and only inside it.
def make_greeting():
message = "Hello from inside" # local
print(message)
make_greeting()
print(message)Each call gets fresh local variables, so functions don't trip over each other's names.
Global variables
A variable created at the top level of a file is global. Functions can read it:
tax_rate = 0.18 # global
def price_with_tax(price):
return price * (1 + tax_rate)
print(price_with_tax(100))Same name, different variables
Assigning to a name inside a function creates a new local variable, even if a global with the same name exists:
count = 10
def reset():
count = 0 # a new local variable; the global is untouched
print("inside:", count)
reset()
print("outside:", count)Changing a global: the global keyword
To assign to a global from inside a function, declare it with global:
visits = 0
def record_visit():
global visits
visits += 1
record_visit()
record_visit()
print(visits)It works, but it makes code harder to follow, because any function might change the value. The cleaner pattern is to pass values in and return results:
def record_visit(visits):
return visits + 1
visits = 0
visits = record_visit(visits)
visits = record_visit(visits)
print(visits)How Python finds a name: LEGB
When you use a name, Python searches four scopes in order:
- Local: inside the current function
- Enclosing: inside any function that contains this one
- Global: the top level of the file
- Built-in: Python's own names, like
lenandprint
The first match wins. That's why naming your own variable list or print is a bad idea: it hides the built-in.
def outer():
label = "enclosing"
def inner():
print(label) # found in the enclosing scope
inner()
outer()