Global vs Local Variables in Python
Understand global vs local variables in Python, the global and nonlocal keywords, the LEGB scope rule, and how to avoid UnboundLocalError with clear examples.
Expected Interview Answer
A local variable is defined inside a function and only exists while that function runs, whereas a global variable is defined at module level and is visible everywhere in the module. To reassign a global from inside a function you must declare it with the global keyword.
When Python resolves a name it follows the LEGB rule: Local, then Enclosing, then Global, then Built-in scope. Reading a global from inside a function works automatically, but assigning to a name inside a function makes it local unless you explicitly use global (module scope) or nonlocal (enclosing function scope). Overusing globals creates hidden coupling, so functions should prefer parameters and return values.
- Local variables keep function state isolated and prevent side effects
- Global variables let you share configuration or constants across a module
- The global keyword makes intentional module-level mutation explicit
- Understanding LEGB avoids UnboundLocalError surprises
- Encourages cleaner, testable functions that rely on arguments over hidden state
AI Mentor Explanation
A local variable is like chalk notes a batter keeps in their own head during a single over — gone the moment the over ends. A global variable is the giant stadium scoreboard every player and fan reads. To change the scoreboard you must go through the official operator, just as changing a global needs the explicit global keyword instead of scribbling privately.
Step-by-Step Explanation
Step 1
Define at module level
Any variable assigned outside all functions and classes is global and visible throughout the module.
Step 2
Define inside a function
Any name first assigned inside a function is local to that call and destroyed when the function returns.
Step 3
Reading vs assigning
Reading a global inside a function works automatically; assigning creates a new local unless you say otherwise.
Step 4
Use global to mutate
Declare 'global name' at the top of the function to reassign the module-level variable instead of shadowing it.
Step 5
Use nonlocal for closures
In a nested function, use 'nonlocal' to rebind a variable in the enclosing (not global) function scope.
What Interviewer Expects
- Clear definition of local and global scope
- Knowledge of the global and nonlocal keywords
- Understanding of the LEGB name-resolution rule
- Awareness of UnboundLocalError and why it happens
- Reasons to avoid overusing global variables
Common Mistakes
- Thinking you need global just to read a global variable
- Forgetting global before assigning, causing UnboundLocalError
- Confusing nonlocal (enclosing scope) with global (module scope)
- Overusing globals and creating hidden coupling between functions
- Assuming a variable defined in an if-block inside a function is somehow global
Best Answer (HR Friendly)
“A local variable lives only inside the function that creates it, while a global variable is shared across the whole file. If a function needs to change a shared value, it has to say 'global' first; otherwise it just makes its own private copy.”
Code Example
counter = 0 # global variable
def increment():
global counter # declare intent to modify the global
counter += 1 # reassigns the module-level counter
def show():
message = 'current count' # local variable, only exists here
print(message, counter) # reading the global works without 'global'
increment()
increment()
show() # -> current count 2
def broken():
print(counter) # UnboundLocalError: assignment below makes counter local
counter = 99
def make_counter():
count = 0
def step():
nonlocal count # rebinds the enclosing count, not a global
count += 1
return count
return step
c = make_counter()
print(c(), c(), c()) # -> 1 2 3
Follow-up Questions
- What is the LEGB rule and how does Python use it to resolve names?
- Why does assigning to a variable inside a function make it local?
- When would you use nonlocal instead of global?
- What problems can excessive use of global variables cause?
- How can you share state between functions without using globals?
MCQ Practice
1. Which keyword lets a function reassign a variable defined at module level?
The global keyword tells Python that assignments inside the function should target the module-level variable rather than create a new local.
2. What does Python's LEGB rule stand for?
Python resolves names by searching Local, then Enclosing, then Global, then Built-in scopes in that order.
3. What happens if you read a variable, then assign to it later, all inside one function without 'global'?
The later assignment makes the name local for the entire function, so the earlier read raises UnboundLocalError.
Flash Cards
What is a local variable? — A variable created inside a function that only exists during that function's execution.
What is a global variable? — A variable defined at module level, visible throughout the module and readable inside functions.
When do you need the global keyword? — Only when you want to reassign a module-level variable from inside a function.
What does nonlocal do? — Rebinds a variable in the nearest enclosing function scope, used in nested functions and closures.
What is the LEGB rule? — Name lookup order: Local, Enclosing, Global, Built-in.