Python Tutorial Python Advanced Python References Python Libraries

Python nonlocal Keyword



The Python nonlocal keyword is used to declare a variable which is not local. A nonlocal variable is generally used inside nested functions where the variable does not belong to the inner function.

Example: Nested functions with nonlocal variable

In the example below, the variable called MyString is declared as nonlocal variable inside the function called InnerFunction. Due to nonlocal scope of variable MyString, its value gets updated to Hello Python! inside inner function and when the function OuterFunction is called in the program, it prints the updated value of MyString.

def OuterFunction():
  MyString = 'Hello World!'
  def InnerFunction():
    nonlocal MyString
    MyString = 'Hello Python!'
  InnerFunction()
  print(MyString)

OuterFunction()

The output of the above code will be:

Hello Python!

Example: Nested functions without nonlocal variable

In the example below, the variable called MyString is not declared as nonlocal variable. Due to this, the value of MyString is not updated and remains Hello World!.

def OuterFunction():
  MyString = 'Hello World!'
  def InnerFunction():
    MyString = 'Hello Python!'
  InnerFunction()
  print(MyString)

OuterFunction()

The output of the above code will be:

Hello World!

❮ Python Keywords