What is Python's global and local scope?
Answer
Python uses LEGB scope rule to resolve names: Local (inside current function), Enclosing (outer function for nested functions), Global (module level), Built-in (Python built-ins). Variables assigned inside a function are local by default. To modify a global variable inside a function, declare it with global varname. To modify an enclosing scope variable (in nested functions), use nonlocal varname. Reading a global variable without modifying it does not require global. Creating a variable with the same name as a global shadows it locally — the global is not affected. Best practice: minimize global state; prefer passing values as arguments and returning results. Constants (by convention in ALL_CAPS) are typically defined at the global/module level.
Previous
What is the difference between deep copy and shallow copy in Python?
Next
What are Python sets?