A global variable is defined outside a function and belongs to the global scope. Python displays it in the global frame, alongside globally defined functions and classes. section 1.4
Name lookup follows LEGB: local, enclosing function, global, then built-ins. Inside a function, Python searches these scopes in order and stops when it finds the name; outside a function, it searches globals and built-ins. section 6.5
Global and local names can coexist, but assignment inside a function normally creates a local name.
- With x = 100 outside foo and x = 200 inside foo, foo prints its local x while the outer x remains 100. section 6.5
- Add global x inside foo to make the assignment target the outer x; calling foo then changes the global value from 100 to 200. section 6.5
- A global name can shadow a built-in: assigning sum = 0 makes sum([10, 20, 30]) fail because Python finds the integer first. section 6.5
Changing a global explicitly
x = 100 def foo(): global x x = 200 print(x) print(x) foo() print(x) The first print shows 100, the function changes the global name, and the final print shows 200. Without global x, foo would bind a local x instead. section 6.5
x = 100 def foo(): global x x = 200 print(x) print(x) foo() print(x)
Step through the global statement example to compare the outer name before and after the function call. section 6.5
Imported names also enter the current global scope. from os import sep defines sep globally, while import os keeps the name under the module object as os.sep. Import * broadly creates global names and is discouraged when unnecessary. section 8.0











