What is the difference between global, nonlocal, and local variables in Python?
What is the difference between global, nonlocal, and local variables in Python?
What is the difference between global, nonlocal, and local variables in Python?
solveurit24@gmail.com Changed status to publish February 13, 2025
- Local variables: Defined inside a function and only accessible within that function.
- Global variables: Defined outside any function and accessible throughout the entire script.
- Nonlocal variables: Defined in an outer function and used in a nested function.
Example:
global_var = 10 # Global variable
def outer_function():
nonlocal_var = 20 # Nonlocal variable
def inner_function():
print(f"Nonlocal variable: {nonlocal_var}")
print(f"Global variable: {global_var}")
local_var = 30 # Local variable
inner_function()
outer_function()
# Output:
# Nonlocal variable: 20
# Global variable: 10solveurit24@gmail.com Changed status to publish February 13, 2025