Variable Scope in Python
Variable scope refers to the area of a program where a variable can be accessed. In Python, there are two main types of variable scope: global scope and local scope.
Global Scope
A variable that is defined outside of any function or class has global scope. This means that the variable can be accessed from anywhere in the program, including from within functions or classes.
Here's an example:
# Define a global variable
x = 5
def print_x():
# Access the global variable
print(x)
print_x() # Output: 5
In the above example, the variable
x
is defined outside of any function, so it has global scope. The function
print_x()
is able to access this variable, since it is defined globally.
Local Scope
A variable that is defined inside a function or class has local scope. This means that the variable can only be accessed from within the function or class where it is defined.
Here's an example:
def print_x():
# Define a local variable
x = 5
print(x)
print_x() # Output: 5
# This will raise a NameError, since x is not defined globally
print(x)
In the above example, the variable
x
is defined inside the function
print_x()
, so it has local scope. The variable cannot be accessed from outside the function, since it is not defined globally.
Modifying Global Variables
Although global variables can be accessed from within functions or classes, they cannot be modified unless they are explicitly declared as global.
Here's an example:
# Define a global variable
x = 5
def modify_x():
# This will raise an UnboundLocalError, since x is not declared global
x += 1
modify_x()
print(x) # Output: 5
def modify_global_x():
global x
x += 1
modify_global_x()
print(x) # Output: 6
In the above example, the function
modify_x()
tries to modify the global variable
x
, but since it is not declared as global, Python raises an
UnboundLocalError
. The function
modify_global_x()
declares
x
as global, so it is able to modify the variable.
Conclusion
Understanding variable scope is important for writing correct and maintainable Python code. By understanding how variables are scoped, you can avoid common errors and write code that is easy to understand and modify.