Course Progress34%
🍎 Python Basics Topic 34 / 100
⏳ 7 min read

Variable Scope

Where a variable lives and who can see it — local vs global scope explained with clear examples.

"Scope is the neighbourhood a variable lives in. A local variable is like a note inside a room — once you leave the room, it is gone."

— ShurAI

What is Scope?

Scope determines where in your program a variable can be seen and used. Python has two main scopes:

🏠
Local Scope
Created inside a function. Only visible within that function. Destroyed when the function finishes.
🌎
Global Scope
Created outside all functions. Visible everywhere in the file. Lives for the entire program.

Local Variables — Stay Inside

python
def make_greeting():
    message = "Hello from inside!"   # LOCAL variable
    print(message)                   # works fine here

make_greeting()        # Hello from inside!

# Try to access outside — ERROR
print(message)          # NameError: name 'message' is not defined

Global Variables — Visible Everywhere

python
website = "ShurAI"         # GLOBAL variable

def show_site():
    print(f"Learning on {website}")   # can READ global

def show_again():
    print(f"Still on {website}")      # also works

show_site()    # Learning on ShurAI
show_again()   # Still on ShurAI
🌎 Global scope — everything can see this
website = "ShurAI"
🏠 def show_site():
can read: website ✓
local var: only here
🏠 def show_again():
can read: website ✓
local var: only here

Same Name — Different Variables

A local variable with the same name as a global is a completely separate variable — it does not change the global:

python
score = 100              # global score

def reset_score():
    score = 0             # NEW local variable, does NOT touch global
    print(f"Inside: {score}")    # 0

reset_score()
print(f"Outside: {score}")    # still 100 — global unchanged!

The global Keyword

If you genuinely need to modify a global variable from inside a function, use the global keyword. Use it sparingly — it can make bugs hard to trace:

python
lives = 3

def lose_life():
    global lives       # tell Python: use the global 'lives'
    lives -= 1
    print(f"Lives left: {lives}")

lose_life()    # Lives left: 2
lose_life()    # Lives left: 1
print(lives)   # 1 — global WAS changed
Best practice: avoid global when possible

Instead of modifying globals, pass values in as parameters and use return to get them back. This makes functions predictable, testable, and easy to understand.

Real Example — Game Score Tracker

python
# Better pattern: pass and return instead of global
def add_points(score, points):
    """Add points and return the new score."""
    return score + points

def check_level(score):
    """Return level name based on score."""
    if score >= 1000: return "🎉 Legend"
    if score >= 500:  return "⚡ Expert"
    if score >= 100:  return "👑 Player"
    return "🚀 Beginner"

score = 0
score = add_points(score, 150)
print(f"Score: {score} — {check_level(score)}")  # 150 — Player
score = add_points(score, 400)
print(f"Score: {score} — {check_level(score)}")  # 550 — Expert

"Keep your functions self-contained. Variables that go in through parameters and come out through return make code you can actually trust."

— ShurAI

🧠 Quiz — Q1

A variable created inside a function is called a _____ variable.

🧠 Quiz — Q2

What happens if you try to use a local variable outside its function?

🧠 Quiz — Q3

If a function assigns score = 0 without global, what happens to the global score?

🧠 Quiz — Q4

What does the global keyword do inside a function?