Himanshu SharmaSoftware engineer
Let’s talk

Python Tutorial · Lesson 38 of 70

Python variable scope: local, global and nonlocal

Understand where Python variables live, how local and global scope differ, what the global and nonlocal keywords do, and the LEGB lookup order.

13 minFunctionsUpdated 14 November 2026

Awaiting technical review. This lesson is readable but not yet listed in search engines.

By the end of this lessonPredict which variable a name refers to inside and outside a function, and use global and nonlocal only when needed.

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.

python
def make_total(price):
    tax = price * 0.1
    return price + tax

print(make_total(200))
result
220.0

Now try to use tax from outside:

python
print(tax)
result
NameError: name 'tax' is not defined

The 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.

python
shop_name = "Corner Shop"

def print_header():
    print("Welcome to", shop_name)

print_header()
result
Welcome to Corner Shop

Reading 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.

python
visitors = 10

def add_visitor():
    visitors = 99
    print("inside:", visitors)

add_visitor()
print("outside:", visitors)
result
inside: 99
outside: 10

The global visitors is untouched. Even more confusing is this variation, where you try to update a global using its own value:

python
visitors = 10

def add_visitor():
    visitors = visitors + 1

add_visitor()
result
UnboundLocalError: local variable 'visitors' referenced before assignment

Python 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.

python
visitors = 10

def add_visitor():
    global visitors
    visitors = visitors + 1

add_visitor()
add_visitor()
print(visitors)
result
12

This 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:

python
def add_visitor_clean(count):
    return count + 1

visitors = 10
visitors = add_visitor_clean(visitors)
print(visitors)
result
11

Notice 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.

python
orders = []

def record(item):
    orders.append(item)

record("tea")
record("bread")
print(orders)
result
['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.

python
def make_counter():
    count = 0
    def step():
        nonlocal count
        count += 1
        return count
    return step

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

Each 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:

  1. Local: the current function.
  2. Enclosing: any functions around it.
  3. Global: the module.
  4. Built-in: names such as len and print.
python
def show():
    print(len("abc"))

show()
len = "shadowed"
print(len)
result
3
shadowed

Naming 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:

python
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]))
result
10
30

Each 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 list or max.

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
python
def make_greeter(greeting):
    def greet(name):
        return f"{greeting}, {name}"
    return greet

welcome = make_greeter("Welcome")
print(welcome("Asha"))
result
Welcome, Asha

Key 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.

Check yourself

1. A variable is first assigned inside a function. Where can it be used?
2. Inside a function you write count = count + 1 where count is only defined at module level. What happens?
3. Which keyword lets an inner function change a variable of the function around it?
4. What does the L in LEGB stand for?