Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 5.5 — Scope and Namespaces: LEGB
Python · Example 1 of 2

LEGB in action

Three different x values, one per scope. A function can read the global x, and len comes from the built-in scope.

Scope decides which names a piece of code can see. Python looks a name up in four places in order: Local, Enclosing, Global, Built-in (LEGB). Assigning to a name inside a function makes it local unless you declare it global or nonlocal.

Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.

Ready for more? This phase has 6 hands-on exercises with automatic checks.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

Write a function show_scopes() with a local variable message = "local" and a global message = "global" defined above it. Print both the local (inside) and the global (outside).

02

Write make_total() that returns an inner function add(n) that adds to a running total and returns it, using nonlocal. Call it with 5 and then 10.

03

Fix this broken function by returning the new value instead of using global: score = 0 and def add_point(): score += 1.

Explain it without notes

01

Explain the LEGB rule.

02

Why does counter += 1 inside a function raise UnboundLocalError?

03

What is the difference between global and nonlocal?

04

What is shadowing a built-in, and how do you avoid it?

LEGB in action
Sign in to run this example in your browser.

Expected output

inner sees: local
outer sees: enclosing
module sees: global
read_only sees: global
a built-in: 3