Python Variable Scope: Local and Global Variables Explained
Learn how local and global variables work in Python, when to use the global keyword, and how scope errors appear in placement coding tests.
Variable scope in Python determines where a name is visible: a local variable lives only inside its function, and a global variable is accessible throughout the program.
Getting this right prevents two of the most common errors in placement coding rounds: NameError and UnboundLocalError. Understanding what Python does with names, and when, is what this article covers.
What Variable Scope Means in Python
Scope is the region of code where a name (variable, function, class) is visible and can be used. Python resolves names by searching through four nested scopes in order, a rule documented in the Python 3 tutorial on scopes and namespaces: Local, Enclosing, Global, and Built-in (abbreviated as LEGB).
For most placement test questions and day-to-day Python code, only two of these four matter: local and global. The examples below cover both in detail.
Local Variables: Confined to the Function
A local variable is any name assigned inside a function body. Python creates it when the function is called and destroys it when the function returns.
def greet():
message = "Hello from inside the function"
print(message)
greet()
# Output: Hello from inside the function
The variable message exists only for the duration of the greet() call. Try to read it after the function returns:
def greet():
message = "Hello from inside the function"
print(message)
greet()
print(message) # NameError: name 'message' is not defined
Python raises a NameError because message no longer exists at the module level. Local variables don’t persist between calls, and they don’t exist outside the function at all.
Global Variables: Readable from Anywhere
A global variable is defined at module level, outside any function. It is readable inside any function in the same module without any special keyword.
message = "Hello from module level"
def greet():
print(message) # reads the global 'message'
greet()
# Output: Hello from module level
Readable, but not automatically writable. If you assign to the same name inside a function without telling Python it is global, Python creates a new local variable and the global remains unchanged. That distinction is where most scope bugs come from.
The global Keyword: Writing Back to Module Level
To modify a global variable from inside a function, declare it with the global keyword before any use of that name in the function body. The Python reference for the global statement specifies that the declaration must appear before any other use of the name in that scope.
count = 0
def increment():
global count
count += 1
increment()
increment()
print(count) # 2
Without the global declaration, count += 1 raises an UnboundLocalError on the first call. Python sees count as a local variable (because of the assignment), then tries to read it before it has been assigned, and fails.
When to use global
Use it sparingly. The typical legitimate case is a shared counter or a flag that multiple functions need to update. When several functions all modify the same global, debugging becomes harder because any one of them could be responsible for an unexpected value. Prefer returning values from functions and passing state explicitly through arguments. The global keyword is a tool for specific situations, not a default pattern.
Name Collisions and the UnboundLocalError Trap
Local and global variables can share a name. When they do, the local version takes priority inside the function.
x = 10
def show():
x = 20 # local x
print(x) # 20
show()
print(x) # 10 (global is unchanged)
That behavior is predictable. The trap that appears in placement tests is subtler:
x = 10
def broken():
print(x) # UnboundLocalError here
x = 20
broken()
This code fails even though x is read before the assignment. Python determines at compile time whether a name is local or global by scanning the entire function body for assignments. The line x = 20 makes Python decide that x is local throughout broken(), including the print(x) line that appears before the assignment. At runtime, Python tries to read the local x, finds it has not been assigned yet, and raises UnboundLocalError.
The fix is to declare global x at the top of the function, or to restructure the function so it does not mix reading a global and assigning a local with the same name.
The same compile-time rule applies in programs of any complexity. The greatest of three numbers function, for instance, uses local variables for its comparison results. Those variables exist only inside the function; referencing them outside would raise NameError.
Scope Questions in Placement Tests
Placement coding rounds use scope questions in two formats:
- Spot the error: a short code snippet is shown; the question asks which error it raises and why. The
UnboundLocalErrortrap above is the most common variant. - Trace the output: a snippet with shadowed names is shown; the question asks what the final
printstatements output.
For the trace-the-output format, apply one rule: inside a function, any assigned name is local unless declared global. For a calculator program question, each operation is a separate function, and scope rules determine whether a result variable accumulates across calls or resets each time.
For sum-of-array style programs, placement questions often put an accumulator at module level and ask whether it changes across multiple calls. The answer depends on whether the function uses global before modifying the accumulator.
The Python basic programs collection covers a broad set of compact functions whose scope behavior you can trace using the rules above. Each is a useful practice case for recognising local versus global patterns under test conditions.
Scope Rules You’ll Use in Every Python Program
The core rules, summarised:
- A name assigned inside a function is local to that function by default.
- A name not assigned inside a function is resolved at the enclosing or global scope.
global nameinside a function removes the local binding and points the name at the module-level object.- Python’s compile-time scope decision means a single assignment anywhere in a function makes the name local throughout the function, including lines before the assignment.
- Accessing an unassigned local raises
UnboundLocalError. Accessing a name that exists at no scope raisesNameError.
Scope errors in Python are mechanical. Once you know the LEGB resolution order and the compile-time local-detection rule, every NameError and UnboundLocalError is predictable before you run the code.
The NameError and UnboundLocalError patterns in this article stop appearing once you write functions that pass state through return values instead of relying on globals. TinkerLLM is where that kind of practice starts with real stakes: ₹299 gives you live LLM API calls, and every function you write to manage prompts, track conversation state, or parse model responses exercises the same scope rules covered here. That practice is what turns these rules from something you read into something you apply correctly the first time.
Primary sources
Frequently asked questions
What is the difference between local and global variables in Python?
A local variable is defined inside a function and accessible only within that function. A global variable is defined at module level and accessible from anywhere in the module, including inside functions.
What happens if I access a local variable outside its function in Python?
Python raises a NameError: name 'variable_name' is not defined. The local variable is destroyed when the function returns, so it no longer exists outside the function scope.
When should I use the global keyword in Python?
Use global when you need to modify a module-level variable from inside a function. If you only need to read the global variable, no keyword is required. Limit global keyword usage to genuine shared-state needs.
What causes UnboundLocalError in Python?
Python decides at compile time whether a variable is local or global based on whether any assignment to that name appears in the function. If an assignment exists, the name is treated as local throughout the function, even in lines before the assignment.
Can local and global variables have the same name in Python?
Yes. Inside the function, the local version takes priority and shadows the global. Outside the function, only the global version is visible. Using the global keyword removes the shadowing and makes both refer to the same object.
What is the LEGB rule in Python?
LEGB stands for Local, Enclosing, Global, Built-in. When Python looks up a name, it searches these four scopes in order and uses the first match it finds.
A self-paced playground for building with LLMs.
TinkerLLM is FACE Prep's sister property. A guided environment for shipping real LLM applications, the kind of project that earns a paragraph on your resume, not a line.
Try TinkerLLM (₹299 launch)