What is the difference between global, nonlocal, and local variables in Python?

95 views

What is the difference between global, nonlocal, and local variables in Python?

What is the difference between globalnonlocal, and local variables in Python?

solveurit24@gmail.com Changed status to publish February 13, 2025
0
  • 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: 10

solveurit24@gmail.com Changed status to publish February 13, 2025
0
You are viewing 1 out of 1 answers, click here to view all answers.