Lesson 10 of 19 · 2 min
Scope — Where Variables Live
Every variable has a scope — the region of code where it is visible and accessible.
- Local scope: Variables created inside a function exist only during that function call. They are destroyed when the function ends.
- Global scope: Variables created outside all functions exist for the entire program's lifetime.
program_name = "Grade Calculator" # GLOBAL — visible everywhere in the file
def compute():
result = 42 # LOCAL — exists only inside compute(), then gone
print(program_name) # functions CAN read global variables
print(result) # can use its own local variable too
compute()
print(program_name) # global still exists after function call
# print(result) # NameError — result was destroyed when compute() ended
Output: Grade Calculator 42 Grade Calculator
Modifying a Global Variable — the global Keyword
counter = 0 # global variable — shared across the whole program
def increment():
global counter # tell Python: "I mean the GLOBAL counter, not a new local one"
counter += 1 # now this modifies the GLOBAL counter
print(f"Counter is now: {counter}")
increment() # 1
increment() # 2
increment() # 3
print(counter) # 3 — change persists between calls
Output: Counter is now: 1 Counter is now: 2 Counter is now: 3 3
Best practice: Avoid
globalwhenever possible. It makes functions unpredictable. Instead, pass the value as a parameter and usereturn.
