After this lesson you can say, for any variable in your code, where it lives and who can see it, and you will know why a global variable is usually a poor tool.
Local variables
Every time a function runs, Python gives it a private workspace. Names created inside, including parameters, belong to that workspace and vanish when the function returns. This is called local scope.
def make_total(price):
tax = price * 0.1
return price + tax
print(make_total(200))220.0Now try to use tax from outside:
print(tax)NameError: name 'tax' is not definedThe last line fails with the error below, and the reason is the point of the lesson. The variable tax existed only inside the call.
Because variables are private, two functions can use the same name without disturbing each other. Local scope is a feature: it keeps the parts of a program from interfering.
Global variables
A name created at the top level of a file is global (more exactly, it belongs to the module). Functions can read it.
shop_name = "Corner Shop"
def print_header():
print("Welcome to", shop_name)
print_header()Welcome to Corner ShopReading a global needs nothing special.
Assigning creates a local
The trouble starts when a function assigns to a name that also exists globally. Python does not change the global. It makes a brand new local with the same name.
visitors = 10
def add_visitor():
visitors = 99
print("inside:", visitors)
add_visitor()
print("outside:", visitors)inside: 99
outside: 10The global visitors is untouched. Even more confusing is this variation, where you try to update a global using its own value:
visitors = 10
def add_visitor():
visitors = visitors + 1
add_visitor()UnboundLocalError: local variable 'visitors' referenced before assignmentPython decides at definition time that visitors is local, because the function assigns to it. Reading it before it has a value fails, so the error mentions a local variable.
The global keyword
To rebind the module-level name, declare it with global at the top of the function.
visitors = 10
def add_visitor():
global visitors
visitors = visitors + 1
add_visitor()
add_visitor()
print(visitors)12This works, but it ties the function to one particular outside variable. Testing it, reusing it and reading it later all become harder. A cleaner design passes the value in and returns the new one:
def add_visitor_clean(count):
return count + 1
visitors = 10
visitors = add_visitor_clean(visitors)
print(visitors)11Notice also that global is only needed to rebind a name. Changing a mutable object, such as appending to a global list, needs no keyword, because you are not assigning to the name.
orders = []
def record(item):
orders.append(item)
record("tea")
record("bread")
print(orders)['tea', 'bread']Enclosing scope and nonlocal
A function can be defined inside another function. The inner one can read the outer one's variables. To rebind them, use nonlocal.
def make_counter():
count = 0
def step():
nonlocal count
count += 1
return count
return step
counter = make_counter()
print(counter())
print(counter())
print(counter())1
2
3Each call to make_counter() creates a separate count, and the returned function remembers it. This is called a closure. It is a neat way to hold a bit of state without a global.
The LEGB rule
When you use a name, Python searches four places in order and stops at the first match:
- Local: the current function.
- Enclosing: any functions around it.
- Global: the module.
- Built-in: names such as
lenandprint.
def show():
print(len("abc"))
show()
len = "shadowed"
print(len)3
shadowedNaming a variable len hides the built-in one, a real bug source. Avoid names such as list, sum, max and str for your variables.
A small worked example
Suppose you are tracking the number of items sold in a day. A beginner often writes a function that edits a global total. Here is the version that keeps the state inside a function instead, using a list to collect values and returning the result:
def total_sold(sales):
running = 0
for amount in sales:
running += amount
return running
today = [3, 5, 2]
print(total_sold(today))
print(total_sold([10, 20]))10
30Each call has its own running, so the two calls never disturb each other, and you did not need any global. When you notice yourself reaching for global, ask whether the value can be a parameter, with the answer coming back through return. It nearly always can.
Common mistakes
- Expecting a local to survive. Once the function returns, its variables are gone. Return what you need.
- Assigning to a global without declaring it. You silently create a local instead.
- Reading a name and assigning it in the same function. Python treats it as local throughout, giving an UnboundLocalError.
- Using global for convenience. Pass parameters instead.
- Shadowing built-in names such as
listormax.
Exercise
Write make_greeter(greeting) that returns an inner function. The inner function takes a name and returns the greeting followed by the name. Create a greeter with "Welcome" and use it for "Asha".
Show one possible answer
def make_greeter(greeting):
def greet(name):
return f"{greeting}, {name}"
return greet
welcome = make_greeter("Welcome")
print(welcome("Asha"))Welcome, AshaKey points
- A variable created inside a function is local. It exists only while the function runs and cannot be seen outside.
- A function can read a global variable, but assigning to the same name inside the function creates a new local one.
- The global keyword lets a function rebind a module-level name, and nonlocal does the same for an enclosing function.
- Python looks names up in the order Local, Enclosing, Global, Built-in (LEGB).
- Prefer parameters and return values over global variables. They make code easier to test and understand.