Scope in Python

The scope in Python refers to the region of the code where a variable is recognized. A variable's scope determines where it can be accessed or modified. Python has the following types of variable scopes:

Local Scope:

Variables declared inside a function are in the local scope and can only be accessed within that function:

Python
def my_function():
    x = 10  # Local scope
    print(x)

my_function()  # Output: 10
# print(x)  # Error: NameError: name "x" is not defined

Global Scope:

Variables declared outside any function are in the global scope and can be accessed anywhere in the code:

Python
x = 10  # Global scope

def my_function():
    print(x)

my_function()  # Output: 10
print(x)  # Output: 10

Global Keyword:

The global keyword allows you to modify a global variable inside a function:

Python
x = 10  # Global scope

def my_function():
    global x
    x = 20

my_function()
print(x)  # Output: 20

Understanding scope is important to control the visibility and lifetime of variables in your programs.