What is the nonlocal keyword in Python?

In this shot, we will discuss the nonlocal keyword in Python.

Variables in Python are mainly of 2 types:

  • Global variables: Declared outside the function or in a global scope.

  • Local variables: Declared inside the function’s body or in a local scope.

The nonlocal keyword is used to work with variables inside nested functions whose local scopes are not defined.

In other words, when we declare a variable as nonlocal, it means it is neither local nor global.

Suppose we have a nested function, as shown in the code snippet below.

# First Function
def f():
x = 10
# Nested Function
def g():
x = 1
g()
print (x)
f()

Expected output

Although we expect the output to be 1, that is not the case. The actual output here will be 10.

Explanation

x = 10 and x = 1 have different IDs, meaning that they are stored as different objects. So, when we call the f() function, the local variable x (which is equal to 10) is returned.

Now, if we want to get x = 1 as the output, we need to add the nonlocal keyword inside the nested function, as shown below.

# First Function
def f():
x = 10
# Nested Function
def g():
nonlocal x
x = 1
g()
print (x)
f()

Explanation

  • In line 2, we initiate our first function.

  • In line 3, we declare a local variable x = 10.

  • In line 6, we declare a nested function.

  • In line 7, we assign the nonlocal keyword to x, as a result of which any defined values of x will now be taken in subsequent entries and the result will be the new x.

  • In line 8, we assign a value of 1 to x.

  • In line 9, we call the g() function, which now carries x = 1 along with it.

  • In line 10, we print the value of x, which comes out to be 1.

  • In line 12, we call the f() function so that the entire function gets executed.

New on Educative
Learn to Code
Learn any Language as a beginner
Develop a human edge in an AI powered world and learn to code with AI from our beginner friendly catalog
🏆 Leaderboard
Daily Coding Challenge
Solve a new coding challenge every day and climb the leaderboard

Free Resources