Command Palette

Search for a command to run...

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

global, nonlocal and shadowing

The last lines shadow the built-in sum on purpose, then remove the shadow with del. The try/except lines catch the error so it can be printed (Topic 7.1).

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?

global, nonlocal and shadowing
Sign in to run this example in your browser.

Expected output

count: 2
5 15
TypeError: 'int' object is not callable
6