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.
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).
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.
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
Explain the LEGB rule.
Why does counter += 1 inside a function raise UnboundLocalError?
What is the difference between global and nonlocal?
What is shadowing a built-in, and how do you avoid it?
Expected output
count: 2
5 15
TypeError: 'int' object is not callable
6