Nonlocal vs Global Keyword in Python

In this tutorial, we will see the basic purpose and use of nonlocal and global keywords in Python. We will also be able to differentiate them from this article.

For Nonlocal and Global keyword Nested Loops are used.

Local:

It is used to work with the variables in the Nested Loop, Where the variables are assigned inside the Function body of the Loop.

Here, The String will update and Print by using the call method which is a defined variable.

String = "Python"
def variable():
    String = "Python Language"
    print(String)
variable()

Global:

It is used to work with the variable in the Nested Loop, Where the variable is assigned at Outside or in global. In Global, the variables can access from inside or outside of the loop.

Here, the variable String can be accessed from inside and outside of the Loop.

String = "Python Language"
def variable():
    print("Inside Loop:", String)
variable()
print("Outside Loop:", String)

Output:

Inside Loop: Python Language

Outside Loop: Python Language

But in the Global variable, it can’t update after the Loop.

String = "Python Language" 
def variable():
    String = String*2 
    print("Inside Loop:", String) 
variable() 
print("Outside Loop:", String)

Output:

line 3, in variable String = String*2

UnboundLocalError: local variable ‘String’ referenced before assignment

 

Non Local:

It is used to work with the variables inside the Nested Loop, Where the variable does not belong to the Inside the Nested Loop or Nested Function.

Non Local indicates that the values of the variables are neither local nor global.

def Outer_String():
    def Inner_String():
       nonlocal String
       String = "Python Language"
    String = "Python"
    Inner_String()
    print("Nonlocal String:", String)
Outer_String()

 

Output:

Nonlocal String: Python Language

Leave a Reply

Your email address will not be published. Required fields are marked *