Stop 04 · FunctionsTopics · 5/8

Variable Scope & the LEGB Rule

Part of the Python Roadmap

In short

Why does changing a variable inside a function not change the one outside? Why do you sometimes get UnboundLocalError? Both come down to scope: where a name lives and where Python looks for it.

Python looks up a name in four places in order: Local, Enclosing, Global, then Built-in (LEGB). Variables created inside a function are local, and you need global or nonlocal to reassign outer ones, which is usually best avoided.

The jaadu peers under a bedroom cushion while a cutaway view of the house shows a living room, a whole home and a building lobby beyond.

Think of it like this

Looking for the TV remote

You lose the remote. First you check your own room (Local). Then the living room you share with family (Enclosing). Then the whole house (Global). Still nothing? You ask the building's common store (Built-in). You always search nearest first and stop at the first place you find it. Python searches for names in exactly that order.

Watch it happen

Where does Python find a name used inside inner()?

Local
Enclosing
Global
Built-in

1/4Looking up city: inner() has its own city = "Pune", so the search stops right here.

The big ideas

What you need to know

Assignment creates a local

Any name you assign inside a function is local to that call, even if a global has the same name. The global is untouched.

Reading outer names is fine

A function can read a global or enclosing variable without any keyword. Problems start only when you try to reassign it.

global and nonlocal

global x lets a function reassign a module-level x. nonlocal x does the same for a variable in the enclosing function.

Prefer passing and returning

Instead of reaching out to change globals, take values as parameters and return new ones. It makes functions predictable and testable.

See it in code

Walk through the code

python
1city = "Delhi"                  # global2 3 4def outer():5    city = "Mumbai"             # enclosing, from inner's point of view6 7    def inner():8        city = "Pune"           # local to inner9        print("inner:", city)10 11    inner()12    print("outer:", city)13 14 15outer()16print("global:", city)17print(len("abc"))               # len comes from the built-in scope18 19visits = 020 21 22def record_visit():23    global visits               # allowed, but use sparingly24    visits += 125 26 27record_visit()28print(visits)                   # 1

1/5A global variable at the top level of the module.

Prints inner: Pune, outer: Mumbai, global: Delhi, 3 and 1. Each assignment stays in its own scope.

Save yourself the pain

Common mistakes

Oops

Writing count += 1 inside a function to update a global count and getting UnboundLocalError.

Do this instead

Better: pass count in and return the new value. If you must, declare global count at the top of the function.

Oops

Expecting a variable created inside a function to exist after the call.

Do this instead

Local names disappear when the function returns. return the value if the caller needs it.

Oops

Naming a variable list, str or sum and then breaking the built-in.

Do this instead

Your global name shadows the built-in. Use names like items, text or total instead.

Your mission

Scope detective

~20 min

Quick check

x = 5; def f(): x = 10. After calling f(), what is the global x?

Go deeper

  1. 1Create a variable with the same name inside and outside a function and print both.
  2. 2Write a nested function that reads a variable from its enclosing function.
  3. 3Prefer passing values in and returning results over using global.

More topics at this stop

Stuck on this topic? Ask an Insider

Get 1:1 guidance from people who've walked this exact path — on the InsideEdge app.

Download
InsideEdge