Python, from Zero, for AILesson 23 of 89

Module 3 · Functions, modules, and code you can read again in March

Where a name lives, and why the function cannot see it

In this lesson

  • 8 min read
  • 6 reading sections
  • Knowledge check
  • Lesson 3 of 9 in this chapter

This chapter’s goalSplit a working script into functions and modules with explicit arguments, return values and docstrings, explain from Python’s scoping rules why a variable changed inside a function did or did not change outside it, and run the result from a terminal with named options.

This chapter’s media

The film explains chapter ideas. The audiobook narrates the complete teaching text.

FormatEnglishहिंदी
Chapter filmWatch1:44Not available
Full audiobookNot availableNot available
How Python decides that a name is localdef is compiledThe whole bodyis scannedbefore any of itrunsAssignedanywhere in thebody?One assignmentcounts, even onthe last lineYes: local forall of itUnless global ornonlocal saysotherwiseRead beforethat lineUnboundLocalError,not NameErrorNo assignmentat allLooked upoutward as itruns: local,enclosing,global, built-inThis is a compile-time decision made from the text of the function, which is why the assignment can beon the last line and still make the name local on the first. UnboundLocalError therefore means theopposite of what it sounds like: not that the name is missing, but that Python knows it is local andknows it has no value yet.
This is a compile-time decision made from the text of the function, which is why the assignment can be on the last line and still make the name local on the first. UnboundLocalError therefore means the opposite of what it sounds like: not that the name is missing, but that Python knows it is local and knows it has no value yet.

Figure

A little at a time

Explore an idea, try it, then check what stays.

Step 1 of 8Free · no account needed
Lesson steps

Four places Python looks for a name

When you use a name, Python searches in this order and stops at the first hit:

  1. Local: names assigned inside the current function.
  2. Enclosing: names in a function that contains this one.
  3. Global: names at the top level of the module.
  4. Built-in: print, len, sum and the rest.

That is the LEGB rule, and it explains both directions of confusion.

Reading a global from inside a function works without ceremony:

Python
TAX_RATE = 0.18

def with_tax(amount):
    return amount * (1 + TAX_RATE)     # fine, found at step 3

Your place and first choices stay on this browser. Classroom credit is recorded separately.

Stuck on something?Ask Divya, your AI tutor

How to cite: Addaly (2026) ‘Where a name lives, and why the function cannot see it’, in Python, from Zero, for AI. Edited by M. Mun. Addaly. Available at: https://addaly.com/learn/python-for-ai/scope-and-globals (Accessed: 29 November 2026).