🌍 Python Variable Scope – Local vs Global Explained Simply | TechTown.in
In Python, variable scope determines where a variable is visible and accessible within your code. If you’ve ever run into NameError or unexpected results, chances are — it was a scope issue.
Let’s simplify the concept of Python scopes so you can write cleaner, bug-free code.
🧠 What is Scope in Python?
Scope defines the visibility of variables. It answers the question:
“Where can I use this variable?”
Python has four types of scopes, often remembered by the acronym LEGB:
- L: Local
- E: Enclosing
- G: Global
- B: Built-in
🔹 Local Scope
Variables defined inside a function are in the local scope.
def greet():
name = "Tanmay"
print(name)
greet() # Output: Tanmay
print(name) # ❌ Error: name is not defined
✅ You can access name only within the function.
🔸 Global Scope
Variables defined outside all functions are global.
x = 10
def show():
print(x)
show() # Output: 10
print(x) # Output: 10
✅ x is available everywhere.
⚠️ Local vs Global Conflict
If you define a variable inside a function with the same name as a global variable, Python will treat it as a new local variable.
x = 50
def modify():
x = 100 # Local variable
print(x)
modify() # Output: 100
print(x) # Output: 50
🎯 The global x remains unchanged.
🔄 Using the global Keyword
You can use global to modify a global variable inside a function:
x = 5
def change():
global x
x = 20
change()
print(x) # Output: 20
✅ global allows changes at the global level from inside a function.
🔁 Enclosing (Nonlocal) Scope
For nested functions, use nonlocal to modify a variable in the enclosing (outer) function scope:
def outer():
x = "Hello"
def inner():
nonlocal x
x = "Hi"
inner()
print(x)
outer() # Output: Hi
🧠 Use nonlocal when you’re dealing with functions inside functions.
🧪 Real-Life Example – Web App Settings
theme = "light"
def toggle_theme():
global theme
if theme == "light":
theme = "dark"
else:
theme = "light"
toggle_theme()
print(theme) # Output: dark
🎯 Useful when your settings need to be accessed or changed globally.
📝 Summary – Python Scope Cheat Sheet
| Scope Type | Defined In | Accessible In |
|---|---|---|
| Local | Inside a function | That function only |
| Global | Outside all functions | Anywhere in the script |
| Enclosing | Outer function (nested) | Inner function |
| Built-in | Python keywords & funcs | Everywhere |
🧩 Tips to Avoid Scope Bugs
- Avoid using the same variable name in different scopes.
- Only use
globalornonlocalwhen necessary. - Always test your functions with different inputs to catch scope issues.
🏁 Final Thoughts
Understanding variable scope in Python is key to writing bug-free and organized code. Whether you’re creating functions, building a project, or nesting functions — scope helps you control data access smartly.
📘 Explore more Python foundations at TechTown.in

