Python: Local, Nonlocal and Global variables

Rahul S
2 min readSep 27, 2023
  • nolocal is used when we need to access a variable in a nested function.global makes a previously declared variable global.

‘nonlocal` and `global` keywords are used to specify the scope of variables within functions and classes. They are used to indicate whether a variable should be treated as a local variable, a nonlocal variable, or a global variable. Here’s what each of these keywords is used for:

1. `local` variables: Variables defined within a function/method are local to that function/method. They can only be accessed within the scope of the function or method in which they are defined.

2. `nonlocal` variables: The `nonlocal` keyword is used within a nested function. It is not local to the nested function but belongs to the nearest enclosing function that is not a global function. We can modify a variable in an outer (enclosing) function’s scope from within an inner function.

def outer_function():
x = 10

def inner_function():
nonlocal x
x = 20

inner_function()
print(x)

# This will print 20
```

3. `global` variables: Variables defined outside any function or at the global scope are global. They can be accessed and modified from any part of the code, including within functions.

--

--