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:
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):
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:
⚠️ 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):
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