Contents
Variable Scope
In Python, we are able to claim variables in three distinctive scopes: local scope, global, and nonlocal scope.
A variable scope specifies the place where we will get entry to a variable. as an instance,
def add_numbers():
sum = 50 + 10
Here, since different codes are created in the role, only the role can be entered (locally). Such changes are called local changes.
According to scope, we can divide Python variables into three types:
- Local Variables
- Global Variables
- Nonlocal Variables
Python Local Variables
When we claim variables internal a function, these variables may have a neighborhood scope (within the characteristic). We cannot access them outdoor the feature.
Example
# Function definition
def coder():
# Local variable
message = ‘Hello’
print(‘Local:’, message)
# Call the coder function
coder()
# Try to access the message variable outside the function
# This will raise a NameError because message is a local variable
# and cannot be accessed outside the function
print(message)
Output
Local: Hello
Traceback (most recent call last):
File “main.py”, line XX, in <module>
print(message)
NameError: name ‘message’ is not defined
Here, the message variable is local to the coder() function, so it can only be accessed within the function
Python Global Variables
In Python, a variable declared outdoor of the characteristic or in worldwide scope is referred to as a global variable. because of this a global variable can be accessed inside or out of doors of the feature.
Example
# Declare a global variable named message
message = ‘programmercoding.com’
# Define the coder function
def coder():
# Attempt to access the global variable message
# Python allows accessing global variables from within functions
print(‘Global:’, message)
# Call the coder function
coder()
# Print the value of the global variable message
print(‘Global:’, message)
Output
Global: programmercoding.com
Global: programmercoding.com
Python Nonlocal Variables
In Python, nonlocal variables are used in nested capabilities whose neighborhood scope isn’t described. which means the variable may be neither inside the neighborhood nor the worldwide scope.
Example
# Define the outer function
def outer():
# Define a local variable named message
message = ‘local’
# Define the inner function
def inner():
# Declare message as nonlocal, indicating it is not local to inner but to outer
nonlocal message
# Assign ‘nonlocal’ to the nonlocal message variable
message = ‘nonlocal’
# Print the value of the message variable inside inner function
print(“inner:”, message)
# Call the inner function
inner()
# Print the value of the message variable outside the inner function
print(“outer:”, message)
# Call the outer function
outer()
Output
inner: nonlocal
outer: nonlocal