Skip to main content
MahiDev — Learn. Build. Become AI-ready.

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.

Intermediate40 min

What you will learn

  • Local vs global variables — where each one lives
  • Why UnboundLocalError happens
  • The global keyword 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.

Global room holds course; function room holds local name and can read course

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() with message = Hello living only inside the function
python
def greet():
    message = "Hello Python"
    print(message)

greet()

# print(message)   # NameError — message disappeared
Created then Used then Destroyed lifecycle of a local variable
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 shared by student1, student2, and student3
python
course = "Python"

def student1():
    print(course)

def student2():
    print(course)

student1()
student2()

Output:

code
Python
Python

Rule: Global variables must exist before the function call, not necessarily before the function definition.


Reading vs modifying globals

This is the most important distinction.

Left: reading count needs no keyword. Right: modifying count needs global
Action global keyword?
Read a global inside a function No
Modify a global inside a function Yes — mandatory
python
count = 10

def show():
    print(count)     # read — safe, no keyword

def inc():
    global count     # modify — required
    count += 1

show()
inc()
print(count)         # 11

Why UnboundLocalError happens

This error confuses almost every beginner.

python
count = 0

def increment():
    count += 1       # UnboundLocalError
count += 1 interpreted as create local, read local, but it does not exist yet

The 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.

python
count = 0

def increment():
    global count
    count += 1

increment()
increment()
increment()
print(count)

Output:

code
3
Function with global count arrow pointing up to modify count = 0

Use global only for variables you intend to modify.


Real example — sales counter

This pattern appears in analytics dashboards.

python
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)
Dashboard cards: 3 transactions and total sales 2450 rupees

Global variables let multiple function calls share one changing state.


Local shadows global

What happens if both variables have the same name?

python
city = "Hyderabad"

def show():
    city = "Mumbai"
    print(city)

show()
print(city)

Output:

code
Mumbai
Hyderabad
Global city Hyderabad; inside function local city Mumbai wins

The local variable shadows the global. The global city is unchanged.


globals() — when you need both values

globals() returns a dictionary of every global variable.

python
city = "Hyderabad"

def show():
    city = "Mumbai"
    print(city)
    print(globals()["city"])

show()
globals() dictionary with city Hyderabad, course Python, score 500

One-liner:

python
globals()["city"]

Think of globals() as Python's global dictionary.

Hyderabad in the global card, Mumbai in the local card

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.

Need x, check local first, then global, else NameError

Local first. If missing, global. If still missing, NameError.


FastAPI-style config

python
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

python
def f():
    x = 10

# print(x)   # NameError

Modifying a global without the keyword → UnboundLocalError

python
count = 0

def bump():
    count += 1    # UnboundLocalError

Thinking 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:

python
score = 100

def test():
    score = 50
    print(score)
    print(globals()["score"])

test()
print(score)
  1. What prints inside the function first?
  2. What does globals()["score"] access?
  3. 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:

  1. Call record_sale(300) once more — transactions should become 4 and total ₹2750.
  2. Change local city to "Delhi" and confirm globals()["city"] stays "Hyderabad".
  3. Comment out global total_sales, transactions and run — you should see UnboundLocalError.

Next: The return Statement.

Loading playground…

Check your understanding

Local and global variables quiz

Where are local variables defined?

1 / 10