Lesson 04
Python Scope — Local Variables, Global Variables, global Keyword and globals()
Understand where Python variables live, why UnboundLocalError happens, when to use the global keyword, and how globals() resolves name conflicts.
What you will learn
- Local vs global variables — where each one lives
- Why
UnboundLocalErrorhappens - The
globalkeyword when you need to modify a global - Local shadowing and
globals()when you need both values - How Python looks up names (scope order)
The big idea
Understand where variables live, why UnboundLocalError happens, when to use the global keyword, and how globals() resolves name conflicts.
Think of Python variables like rooms in a building.
Memory rule
- Global = shared by everyone
- Local = private to one function
This continues from Parameters and Arguments.
What is a local variable?
A local variable exists only while the function is running.
def greet():
message = "Hello Python"
print(message)
greet()
# print(message) # NameError — message disappeared| Property | Local variable |
|---|---|
| Created | When the function starts |
| Lifetime | During function execution |
| Accessible | Only inside the function |
| Destroyed | After return |
What is a global variable?
A global variable is defined in the main program and shared by multiple functions.
course = "Python"
def student1():
print(course)
def student2():
print(course)
student1()
student2()Output:
Python
PythonRule: Global variables must exist before the function call, not necessarily before the function definition.
Reading vs modifying globals
This is the most important distinction.
| Action | global keyword? |
|---|---|
| Read a global inside a function | No |
| Modify a global inside a function | Yes — mandatory |
count = 10
def show():
print(count) # read — safe, no keyword
def inc():
global count # modify — required
count += 1
show()
inc()
print(count) # 11Why UnboundLocalError happens
This error confuses almost every beginner.
count = 0
def increment():
count += 1 # UnboundLocalErrorThe left side of += makes Python treat count as a local variable. The local does not exist yet, so Python raises UnboundLocalError.
The global keyword
Tell Python explicitly: use the global variable, not a local one.
count = 0
def increment():
global count
count += 1
increment()
increment()
increment()
print(count)Output:
3Use global only for variables you intend to modify.
Real example — sales counter
This pattern appears in analytics dashboards.
total_sales = 0
transactions = 0
def record_sale(amount):
global total_sales, transactions
total_sales += amount
transactions += 1
record_sale(500)
record_sale(1200)
record_sale(750)
print("Transactions:", transactions)
print("Total sales: ₹", total_sales)Global variables let multiple function calls share one changing state.
Local shadows global
What happens if both variables have the same name?
city = "Hyderabad"
def show():
city = "Mumbai"
print(city)
show()
print(city)Output:
Mumbai
HyderabadThe local variable shadows the global. The global city is unchanged.
globals() — when you need both values
globals() returns a dictionary of every global variable.
city = "Hyderabad"
def show():
city = "Mumbai"
print(city)
print(globals()["city"])
show()One-liner:
globals()["city"]Think of globals() as Python's global dictionary.
global vs globals()
| Feature | global |
globals() |
|---|---|---|
| Purpose | Modify a global variable | Read the global dictionary |
| Returns | Nothing | dict |
| Used for | Updating shared state | Resolving name conflicts |
| Example | global count |
globals()["count"] |
Scope lookup
This is how Python searches for a name.
Local first. If missing, global. If still missing, NameError.
FastAPI-style config
DB_NAME = "property_db" # global config
def connect():
print(DB_NAME)
def health():
print(DB_NAME)
connect()
health()Why make DB_NAME global?
- One shared configuration
- Avoid duplication
- Easy maintenance
Avoid globals for changing business data like user balances — prefer function parameters or classes.
Common mistakes
Accessing a local outside the function → NameError
def f():
x = 10
# print(x) # NameErrorModifying a global without the keyword → UnboundLocalError
count = 0
def bump():
count += 1 # UnboundLocalErrorThinking a local change updates the global
Same name ≠ same variable. Local city = "Mumbai" does not change global city.
Using globals everywhere
Good for configuration. Bad for application state.
Interview cheat sheet
| Question | Answer |
|---|---|
| Local variable | Exists inside the function only |
| Global variable | Shared across functions |
| Read a global | No keyword needed |
| Modify a global | global keyword required |
globals() returns |
Dictionary |
| Same name local vs global | Local wins |
| Error modifying global without keyword | UnboundLocalError |
| Error accessing local outside | NameError |
Mini challenge
Predict the output without running it:
score = 100
def test():
score = 50
print(score)
print(globals()["score"])
test()
print(score)- What prints inside the function first?
- What does
globals()["score"]access? - What prints after the function ends?
If your answers are 50, 100, 100, you have understood Python variable scope.
The playground already runs this challenge. Confirm, then change the local score and re-run.
Practice in the playground
The playground at the bottom of this page already runs local, global, the sales counter, shadowing, and globals(). Try:
- Call
record_sale(300)once more — transactions should become4and total₹2750. - Change local
cityto"Delhi"and confirmglobals()["city"]stays"Hyderabad". - Comment out
global total_sales, transactionsand run — you should seeUnboundLocalError.
Next: The return Statement.
Loading playground…
Check your understanding
Local and global variables quiz
Where are local variables defined?
1 / 10