Variable Scope and Namespaces
Learn where variables can be used and how Python finds them
What You'll Learn
- What scope means
- Local vs global variables
- Using global keyword
- Best practices
What is Scope?
Scope is where a variable can be used. Think of it as the variable's "zone of influence".
Two types:
- Local - Inside a function only
- Global - Everywhere in the file
Local Variables
Created inside a function, only work inside:
def greet():
message = "Hello" # Local variable
print(message)
greet() # Works: Hello
print(message) # Error! message doesn't exist hereExample:
def calculate():
result = 10 + 5 # Local to this function
return result
print(calculate()) # 15
print(result) # Error! result only exists in functionGlobal Variables
Created outside functions, work everywhere:
name = "John" # Global variable
def greet():
print(f"Hello {name}") # Can read global
greet() # Hello John
print(name) # JohnReading vs Changing
Can read global variables:
count = 0 # Global
def show_count():
print(count) # Reading is OK
show_count() # 0Cannot change without global:
count = 0 # Global
def increment():
count = count + 1 # Error! Can't change global
increment() # UnboundLocalErrorUsing global Keyword
Tell Python you want to change a global variable:
count = 0 # Global
def increment():
global count # Now we can change it
count = count + 1
increment()
print(count) # 1
increment()
print(count) # 2Example: Game score
score = 0
def add_points(points):
global score
score += points
print(f"Score: {score}")
add_points(10) # Score: 10
add_points(5) # Score: 15
add_points(20) # Score: 35Local Shadows Global
Local variable hides global with same name:
x = 10 # Global
def test():
x = 5 # Local (different from global)
print(x)
test() # 5 (local)
print(x) # 10 (global unchanged)Practice Examples
Example 1: Counter
counter = 0
def count_call():
global counter
counter += 1
print(f"Function called {counter} times")
count_call() # Function called 1 times
count_call() # Function called 2 times
count_call() # Function called 3 timesExample 2: Settings
debug_mode = False
def toggle_debug():
global debug_mode
debug_mode = not debug_mode
status = "ON" if debug_mode else "OFF"
print(f"Debug mode: {status}")
toggle_debug() # Debug mode: ON
toggle_debug() # Debug mode: OFFExample 3: Bank account
balance = 1000
def deposit(amount):
global balance
balance += amount
print("Deposited $" + str(amount) + ". Balance: $" + str(balance))
def withdraw(amount):
global balance
if amount <= balance:
balance -= amount
print("Withdrew $" + str(amount) + ". Balance: $" + str(balance))
else:
print("Insufficient funds!")
deposit(500) # Deposited $500. Balance: $1500
withdraw(200) # Withdrew $200. Balance: $1300Best Practices
1. Avoid global when possible:
# Not good
total = 0
def add(x):
global total
total += x
# Better - use parameters and return
def add(total, x):
return total + x
result = add(0, 5)2. Pass parameters instead:
# Not good
name = "John"
def greet():
global name
print(f"Hello {name}")
# Better
def greet(name):
print(f"Hello {name}")
greet("John")3. Return values instead:
# Not good
result = 0
def calculate(x, y):
global result
result = x + y
# Better
def calculate(x, y):
return x + y
result = calculate(5, 3)Nested Functions
Functions inside functions:
def outer():
x = 10 # Outer function variable
def inner():
print(x) # Can read outer variable
inner()
outer() # 10Using nonlocal:
def outer():
x = 10
def inner():
nonlocal x # Change outer function variable
x = 20
inner()
print(x)
outer() # 20Common Mistakes
Mistake 1: Forgetting global
count = 0
def increment():
count += 1 # Error! Need global
# Correct
def increment():
global count
count += 1Mistake 2: Overusing global
# Bad - too many globals
total = 0
count = 0
average = 0
# Better - use function parameters
def calculate_stats(numbers):
total = sum(numbers)
count = len(numbers)
average = total / count
return total, count, averageMistake 3: Shadowing unintentionally
name = "Global"
def test():
name = "Local" # Created new local, didn't change global
print(name)
test() # Local
print(name) # Global (unchanged)When to Use Global
Good uses:
- Configuration settings
- Application state
- Constants (values that don't change)
# Constants (uppercase names)
MAX_USERS = 100
DEBUG = True
API_KEY = "abc123"
def check_users(count):
if count > MAX_USERS:
print("Too many users!")Avoid for:
- Passing data between functions (use parameters)
- Temporary calculations (use local variables)
- Return values (use return statement)
Quick Reference
Read global:
x = 10
def func():
print(x) # Just read, no keyword neededChange global:
x = 10
def func():
global x
x = 20Local variable:
def func():
x = 10 # Only exists in functionNested function:
def outer():
x = 10
def inner():
nonlocal x
x = 20Summary
- Local variables live inside functions
- Global variables live outside functions
- Use
globalkeyword to change globals - Prefer parameters and return values
- Avoid global variables when possible
- Use constants (CAPS_NAMES) for settings
Congratulations!
You've completed the Python basics! You now know:
- Variables and data types
- Operators and conditions
- Loops and functions
- Scope and namespaces
You're ready to build real Python projects!