Python Global, Local and Nonlocal

www.igif‮it‬dea.com

In Python, variables can have different scopes, depending on where they are defined. The three main scopes are global, local, and nonlocal.

  • Global scope: Variables defined outside of any function or class have global scope. They can be accessed from anywhere in the program, including inside functions and classes.

  • Local scope: Variables defined inside a function have local scope. They can only be accessed from within the function where they are defined.

  • Nonlocal scope: Variables defined in an enclosing function can be accessed from within nested functions, but not from the global scope or other functions that are not nested within the enclosing function. These variables are defined using the nonlocal keyword.

Here's an example that demonstrates the use of global, local, and nonlocal variables in Python:

x = 10  # global variable

def foo():
    y = 20  # local variable
    print(x)  # access global variable
    print(y)  # access local variable

def bar():
    x = 30  # local variable with same name as global variable
    print(x)  # access local variable

def baz():
    nonlocal x  # use nonlocal keyword to access variable from enclosing function
    x = 40  # modify nonlocal variable
    print(x)  # access nonlocal variable

foo()  # Output: 10 20
bar()  # Output: 30
baz()  # Output: 40
print(x)  # Output: 40 (global variable modified by baz)

In this example, we define a global variable x with a value of 10. We define three functions, foo(), bar(), and baz(), that demonstrate the use of local, global, and nonlocal variables. foo() defines a local variable y and accesses the global variable x. bar() defines a local variable x with the same name as the global variable, and baz() uses the nonlocal keyword to modify the variable x from the enclosing function.

When we call the functions and print their output, we can see that the global variable is accessible from all the functions, while the local and nonlocal variables are only accessible from within their respective functions. We also see that modifying a nonlocal variable using the nonlocal keyword affects the variable in the enclosing function.