Skip to content
Kuza Ndoto Academy

Variable Scope

Beginner → IntermediateChapter 5 · Page 28 of 564 min readUpdated 15 Nov 2026

A variable's scope is the part of a program where that variable can be seen and used. Variables created inside a function are local to it, while variables created at the top level of a file are global. Understanding scope prevents some of the most confusing bugs beginners meet.

Local variables

A variable assigned inside a function, including its parameters, exists only while that function runs. Code outside the function can't see it.

county = "Nakuru"            # global

def show_town():
    town = "Naivasha"        # local to show_town
    print(town, "is in", county)

show_town()
print(county)
Naivasha is in Nakuru Nakuru

Adding print(town) at the bottom of this program would raise a NameError, because town stopped existing when show_town() finished. This is a good thing: each function has its own private workspace, so variables in different functions can't clash.

Global variables

A variable created outside all functions is global. Functions can read it, as show_town() read county above.

Same name, different variables

If a function assigns to a name that also exists globally, it creates a new local variable that hides (or "shadows") the global one. The global is untouched.

score = 10

def play():
    score = 99               # a new local variable
    print("Inside:", score)

play()
print("Outside:", score)
Inside: 99 Outside: 10

The UnboundLocalError trap

Python decides whether a name is local by looking at the whole function before running it. If the function assigns to a name anywhere, that name is local throughout the function, even on lines before the assignment.

count = 0

def increase():
    count = count + 1        # count is local here, but has no value yet
    print(count)

increase()
UnboundLocalError: cannot access local variable 'count' where it is not associated with a value

Because increase() assigns to count, Python treats count as local. Reading it on the right-hand side happens before any local value exists, so the program fails.

The global keyword

To change a global variable from inside a function, declare it with global first.

count = 0

def increase():
    global count
    count += 1

increase()
increase()
print(count)
2
Warning

Use global sparingly. When many functions change the same global variable, it becomes hard to tell which one caused a wrong value. The cleaner approach is usually to pass values in as arguments and send results back with return.

def increase(count):
    return count + 1

count = 0
count = increase(count)
count = increase(count)
print(count)
2

This version does the same job, but the function depends only on its input, which makes it easier to test and reuse.

Changing vs. reassigning a mutable global

There's an important difference between reassigning a name and changing the object it refers to. Calling a method such as append() on a global list doesn't assign to the name, so no global statement is needed.

attendance = []

def mark_present(name):
    attendance.append(name)    # changes the list; no assignment to the name

mark_present("Zawadi")
mark_present("Kevin")
print(attendance)
['Zawadi', 'Kevin']

Nested functions and nonlocal

A function can be defined inside another function. The inner function can read the outer function's variables. To change one, declare it nonlocal, the nested-function cousin of global.

def make_counter():
    count = 0
    def step():
        nonlocal count
        count += 1
        return count
    return step                 # return the inner function itself

counter = make_counter()
print(counter())
print(counter())
print(counter())
1 2 3

The inner function remembers count even after make_counter() has finished. This is called a closure, and it is the idea behind decorators.

The LEGB rule

When you use a name, Python searches four scopes in order and uses the first match:

  1. Local: inside the current function.
  2. Enclosing: inside any outer functions (for nested functions).
  3. Global: the top level of the file.
  4. Built-in: Python's own names, such as print, len and list.
Built-in: print, len, list, sum … Global: names at the top of the file, e.g. count Enclosing: make_counter() and its count Local: inside step() Python looks here first, then outwards L → E → G → B
Figure 1. Each scope sits inside the next. A name is looked up from the innermost box outwards, and the first match wins, which is why a global named list hides the built-in one.
Common mistake

Because the global scope is searched before built-ins, naming a variable list, sum or input hides the real function for the rest of the file. After list = ["a", "b"], calling list("xyz") fails with TypeError: 'list' object is not callable. Choose names like names or total instead.

Key points

  • Variables assigned inside a function are local and disappear when it returns.
  • Functions can read globals, but assigning to a name makes it local for the whole function.
  • global and nonlocal let you reassign outer variables; prefer parameters and return values.
  • Calling methods on a mutable global (like append()) needs no declaration.
  • Python looks names up in the order Local, Enclosing, Global, Built-in (LEGB).
Up next · FunctionsLambda FunctionsSmall anonymous functions.
→

Tip: use the ← and → keys to move between pages.