A global variable is defined in the main program scope, also called the global scope. A function can read a global variable when its name is not found in the function’s own scope. Python searches outward through enclosing scopes until it reaches the global scope. section 22.2
Two variables with the same name
In `fairy_tale()`, `peter = 5` belongs to the function scope. The later `peter = 30` belongs to the global scope. Calling the function prints 5, while the final global `print(peter)` prints 30. The same name refers to separate variables because the variables occupy different scopes. section 22.2
Listing 22.1. Defining variables with the same name in different scopes
def fairy_tale(): #1
peter = 5 #2
print(peter) #3
peter = 30 #4
fairy_tale() #5
print(peter) #6
Trace the function call and compare the function-scoped `peter` with the global `peter`. section 22.2
Keep these rules in mind:
- A function may access a global variable without defining a same-named variable locally. section 22.2
- Assigning to a name inside a function does not modify the global variable as shown; the function must define its own variable first, or the operation produces an error. section 22.2
- A local variable can temporarily hide a global variable with the same name. section 22.2
- Nested functions add another scope: an inner function can use names available in its enclosing function, while the global scope contains only the outer definition. section 22.3











