Variable Scope
Understand local and global variable scope in functions.
Variable scope determines where variables can be accessed in your code. Understanding scope is essential for writing bug-free functions and avoiding naming conflicts.
π Concepts & Theory
Variable scope defines where a variable can be accessed. Python has local, global, and nonlocal scopes.
Local Scope:
Variables created inside a function exist only within that function:
def my_function():
local_var = 10 # Only exists inside function
print(local_var) # Works
my_function()
print(local_var) # β NameError: not defined
Global Scope:
Variables defined outside all functions are global:
global_var = 10 # Global scope
def my_function():
print(global_var) # β
Can read global
my_function() # Prints 10
Cannot Modify Global Without Declaration:
counter = 0
def increment():
counter = counter + 1 # β UnboundLocalError!
# Python thinks counter is local
global Keyword:
counter = 0
def increment():
global counter # Declare as global
counter = counter + 1 # β
Now works
increment()
print(counter) # 1
Local vs Global Priority:
x = "global"
def func():
x = "local" # Different variable (shadows global)
print(x) # "local"
func()
print(x) # "global"
Parameter Names Don't Conflict:
x = 10
def func(x): # Parameter x shadows global x
print(x) # Uses parameter, not global
func(5) # Prints 5
print(x) # Still 10
Nested Functions - Nonlocal:
def outer():
x = 10
def inner():
nonlocal x # Refers to outer()'s x
x = 20
inner()
print(x) # 20
outer()
Scope Resolution (LEGB Rule):
Python searches for variables in this order:
- Local - Current function
- Enclosing - Parent functions
- Global - Module level
- Built-in - Python built-ins
x = "global"
def outer():
x = "enclosing"
def inner():
x = "local"
print(x) # "local" (found in L)
inner()
outer()
Best Practices:
- β Avoid global variables when possible
- β Use parameters and return values instead
- β Keep scope as narrow as possible
- β Don't modify globals inside functions (hard to track)
- β Don't shadow built-ins (list, str, etc.)
# β Trying to modify global without declaration
total = 0
def add(n):
total += n # Error!
# β
Use return instead
total = 0
def add(n):
return total + n
total = add(5)
π― Your Challenge
Create a counter() function that uses a global variable count, increments it, and returns the new value.
π Starter Code
count = 0
def counter():
pass
- Use the global keyword before modifying the variable
- The syntax is: global variable_name
- Put the global declaration at the start of the function
- Increment count using +=
- Return the incremented value
Solution
count = 0
def counter():
global count
count += 1
return count
Explanation
This function demonstrates the global keyword, which is necessary to modify global variables from within a function. Without global count, Python would create a new local variable named count when we try count += 1, causing an UnboundLocalError. The global declaration tells Python to use the module-level count variable instead. The function increments count by 1 and returns the new value. Each call to counter() increases the global count: first call returns 1, second returns 2, etc. While this works, using global variables is generally discouragedβparameters and return values are cleaner.
β οΈ Common Mistakes to Avoid
- Forgetting the global keyword (causes UnboundLocalError)
- Declaring global after using the variable
- Creating a local variable with the same name by accident
- Not understanding that reading globals works, but modifying requires global
- Using global when parameters/return would be better