Scopes in Python
In Python, a scope is a region of a program where a namespace is directly accessible. A namespace is a container that holds a collection of names (variables, functions, classes, etc.) and provides a mapping from names to objects. Scopes help in organizing and managing namespaces in a Python program.
There are two main types of scopes in Python:
Local Scope:
def my_function():
x = 10 # Local variable
print(x)
my_function()
# print(x) # This would result in an error because x is not defined in this scope
Global Scope:
y = 20 # Global variable
def another_function():
print(y) # Accessing the global variable
another_function()
global
keyword, Python assumes it is a local variable, even if a variable with the same name exists in the global scope. To modify a global variable from within a function, the global
keyword is used.z = 30 # Global variable
def modify_global():
global z
z = 40
print(z)
modify_global()
print(z) # The global variable has been modified
Enclosing (or Nonlocal) Scope:
def outer_function():
a = 50 # Enclosing variable
def inner_function():
print(a) # Accessing the enclosing variable
inner_function()
outer_function()
Understanding and managing variable scopes is crucial for writing correct and maintainable Python code. It helps prevent naming conflicts, ensures proper variable access, and contributes to the overall structure of the program.
Thank you.