Why does a function read a variable but fail to change it? Start by asking where Python finds the name. A scope sets a boundary for name lookup; its namespace tracks the names available there. LEGB is the order Python searches for a name’s referenced object. section 10.4.1 section 10.4
Python searches in this order and stops when it finds the name:
- Local: the current function’s scope. section 10.4.1
- Enclosing: an outer function’s scope, when functions are nested. section 10.4.1
- Global: the module’s scope. section 10.4.1
- Built-in: names such as `print` and `int`. If no scope contains the name, Python raises `NameError`. section 10.4.1
Why a database filename stays unchanged
This assignment creates a local `db_filename`; it does not update the module-level name: ```python db_filename = "N/A" def set_database(db_name): db_filename = db_name set_database("tasks.sqlite") print(db_filename) # N/A ``` To update the module-level variable, declare it `global` before assigning: ```python db_filename = "N/A" def set_database(db_name): global db_filename db_filename = db_name set_database("tasks.sqlite") print(db_filename) # tasks.sqlite ``` section 10.4 section 10.4.2
Use `global` when a function must update a module-level variable, not merely read it: an ordinary read can reach the global scope through LEGB. For a variable in an enclosing function rather than the module, the corresponding declaration is `nonlocal`. When names repeat across scopes, check which scope will supply the value—and whether the code is reading or assigning it. section 10.4.2 section 10.6 section 10.4.4


