Chapter 5: Functions / Lesson 29

Variable Scope

Understanding Variable Scope

Variable scope determines where in your code a variable can be accessed. Python has two main scopes: local (inside functions) and global (outside functions). Understanding scope prevents bugs and helps you write cleaner code.

Variables defined inside a function are local to that function and cannot be accessed outside. Variables defined outside functions are global and can be accessed anywhere.

Local Variables

Variables created inside a function are local to that function. They only exist while the function is executing and cannot be accessed from outside:

local_scope.py
# Local variable inside a function def my_function(): local_var = "I'm local!" # Local variable print(local_var) my_function() # Output: I'm local! # print(local_var) # ERROR! local_var doesn't exist outside the function # Each function has its own local scope def function1(): x = 10 print(x) def function2(): x = 20 # Different x, different scope print(x) function1() # Output: 10 function2() # Output: 20

Global Variables

Variables defined outside functions are global and can be accessed from anywhere in the program, including inside functions (but not modified without the global keyword):

global_scope.py
# Global variable global_var = "I'm global!" def access_global(): print(global_var) # Can read global variables access_global() # Output: I'm global! print(global_var) # Output: I'm global! # Reading vs modifying count = 0 # Global variable def increment(): print(count) # Can read # count += 1 # ERROR! Cannot modify without 'global' increment()

The global Keyword

To modify a global variable inside a function, you must use the global keyword. This tells Python you want to use the global variable, not create a local one:

global_keyword.py
# Using global keyword to modify global variables counter = 0 def increment(): global counter # Declare we're using the global variable counter += 1 print(counter) increment() # Output: 1 increment() # Output: 2 print(counter) # Output: 2 # Example: Score tracking score = 0 def add_points(points): global score score += points print(f"Score: {score}") add_points(10) # Score: 10 add_points(5) # Score: 15

⚠️ Important Note

Use the global keyword only when necessary. Modifying global variables can make code harder to debug. Prefer returning values from functions instead.

Scope Hierarchy

Python searches for variables in a specific order: local scope first, then global scope. This is called the LEGB rule (Local, Enclosing, Global, Built-in):

scope_hierarchy.py
# Variable name resolution x = "global" # Global variable def test(): x = "local" # Local variable (hides global) print(x) # Output: local (uses local) test() print(x) # Output: global (global unchanged) # Reading global when no local exists y = "global y" def read_global(): print(y) # Reads global (no local y exists) read_global() # Output: global y

Best Practices

✅ Scope Best Practices

• Use local variables whenever possible

• Avoid modifying global variables inside functions

• Use function parameters and return values instead

• Only use global when absolutely necessary

💡 Key Concepts

• Local variables: Created inside functions, only accessible there

• Global variables: Created outside functions, accessible everywhere

global keyword: Required to modify global variables

• Scope hierarchy: Local takes precedence over global

🎉

Lesson Complete!

Great work! Continue to the next lesson.

main.py
📤 Output
Click "Run" to execute...