Scope determines where a name can be accessed and how long its binding exists. In Python, functions and modules create namespaces that organize variable names and prevent unrelated code from sharing every value. section 2.3.4
A module-level variable is available throughout its module and generally lasts as long as the imported module. A function-level variable is available only while that function runs. Code inside a function can access suitable names from its containing module scope. section 2.3.4
The same name can resolve differently depending on where it is created:
- Module scope: define prefix outside functions, making it accessible across the module and to code that imports the module. section 2.3.4
- Function scope: define prefix inside add(), so that local value takes precedence when the function runs. section 2.3.3
- Nested access: let my_message() use the module-level prefix while keeping new_message local to the function. section 2.3.4
The same name at two levels
With prefix = "added" at module level, add(12, 12) returns "added: 12 12". If add() assigns prefix = "inside add function", its local value is used instead. The inner binding changes the function’s result without changing the module-level binding. section 2.3.3
Use the scope diagram to see how module and function scopes nest and where a variable is visible. section 2.3.4




















