Learning Sections show
Local vs Global Variables in Python
Understanding the scope of variables is crucial in programming. In Python, variables can be classified as local or global depending on where they are declared and used.
Global Variables
Global variables are defined outside of all functions and can be accessed anywhere in the code.
# This is a global variable
x = 10
def print_global():
# Accessing global variable inside a function
print(x)
print_global() # Output: 10
Local Variables
Local variables are declared inside a function and can only be accessed within that function.
def print_local():
# This is a local variable
y = 5
print(y)
print_local() # Output: 5
# Trying to access local variable outside its scope will cause an error
print(y) # NameError: name 'y' is not defined
Global Keyword
The global
keyword allows you to modify a global variable inside a function.
z = 20
def modify_global():
global z
z = 30
modify_global()
print(z) # Output: 30
Nonlocal Keyword
The nonlocal
keyword allows you to modify a variable in the nearest enclosing scope (excluding global scope).
def outer_function():
a = 10
def inner_function():
nonlocal a
a = 20
inner_function()
print(a) # Output: 20
outer_function()