intermediate

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.)
Common Mistakes:
# ❌ 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

Python
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

Python
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

❓ Frequently Asked Questions

Python allows reading global variables but assumes any variable you assign to is local unless you declare it global.
Generally no. They make code harder to test and maintain. Prefer passing parameters and returning values.
global refers to module-level variables. nonlocal refers to variables in enclosing function scopes.
Yes! The parameter shadows (hides) the global within the function scope.

πŸ”— Related Exercises