Python Global, Local and Nonlocal Variables

    Welcome to the TGB Python tutorials. In this tutorial, we will discuss the variable used in Python and how a variable is categorized into global, local, and non-local categories. Also, we will discuss the global keyword. So let us get started!

    Python Global Local Nonlocal Variables

    Python has three types of variables:

    1. Global variables,
    2. Local variables, and
    3. Nonlocal variables

    1. Python Global Variables

    All those variables in Python that are declared outside the function in a global scope are known as global variables. In simple words, any statement of the program can access a global variable.

    Let’s understand it with an example:

     global_variable = 20                                      #Global Variable
    
    def func():           #defining a function
        print("the value of global_variable is " + str(global_variable))
    
    func()                    #function calling

    #Output

    the value of global_variable is 20

    Behind the code

    In the above example, we first declared a variable with the name global_variable and assigned value 20 to it, and then we defined a function func (), which is printing the output value of global_variable. When we are calling the function func() , it starts execution, and it reaches the print statement and at the print() statement, first the function looks for the globlal _ variable inside itself, but when it could not find it inside func() , then it starts looking for it outside the function and then prints the value.

    2. Python Local Variables

    All those variables that we define inside the function are known as local variables. Also, you cannot access them outside the function.

    Let’s understand it with an example:

    g = "global variable"
    
    def local():
        l = "local variable"
        print(g)    # printing global variable
        print(l)    # print local variable
    
    local()

    #Output

    global variable
    local variable

    Behind the code

    In the above example, g is a global variable, and l is a local variable. You can see that we can access g inside the function local , and we can access it outside the function, but if you try to access the variable l outside the function, it will throw an error.

    Let’s call a local variable outside the function:

    def local():
        l = "local variable"                       # l is a local variable
    
    local()
    print(l)                  # Accessing local variable outside the function

    #Output

    NameError: name 'l' is not defined

    Behind the code

    As evident from the output, we cannot access the local variable outside the function. If we try to access it, we will get an error, such as "variable not defined."

    3. Python Nonlocal Variables

    The nonlocal is a keyword that acts as a global keyword for the nested function (function inside another function). We use the nonlocal keyword when a variable is in local scope but acts as a global scope for another function.

    Let’s understand it with an example:

    def local():
        x = 70
        
        def in_local():
            nonlocal x      #here we grab the actual x variable which is a local variable
            x = 70000
            print("value of x inside the in_local function is", x)
    
        in_local()      #calling function in_local
        print("the value of x inside the function local has become", x)
    
    local()

    #Output

    value of x inside the in_local function is 70000
    the value of x inside the function local has become 70000

    Behind the function

    Though variable x of the local() function is a local variable, it act as global variable for the function in_local(). When we use the keyword nonlocal to grab the variable x and use it inside the nested function, i.e., in_local() , every change we make inside the in_local function on variable x reflects back on the original value of x .

    Global Keyword in Python

    global is a keyword in Python which helps to access the actual global variable from outside the function. Until now, we know that we can access the global variable from outside the function, but if you alter the global variable or assign a new object or value to it inside the function, it will become a local variable, and this has no impact on the actual global variable that is present outside the function. If you want to grab a variable that is outside the function and want to make changes there, we need the global keyword. It can grab the global variable, and we can alter them inside the function.

    Let’s understand it with an example.

    global_variable_1 = 20
    global_variable_2 = 30
    
    def local():
    
        global global_variable_1    #here we have access the actual global_variable_1 which is present outside the function
        global_variable_2 = 70      #it is a local variable having the same name as the global variable
        global_variable_1 = 80      #here we have changed the value of globle_variable_1 which will reflect outside the function too
    
    
    local()
    print("the value of global_variable_1 has become",  global_variable_1)
    print("the value of global_variable_2 did not change" ,  global_variable_2)

    #Output

    the value of global_variable_1 has become 80
    the value of global_variable_2 did not change 30

    Behind the code

    In the above example, we have used the global keyword to access the global_variable_1 inside the local() function. Inside the local() function, we have two variables, namely global_variable_1 and global_variable_2 . global_variable_1 is the same variable that is defined outside the local() function, and the global_variable_2 is the newly created local variable for the local() function. When we changed the values of both the variables inside the function only the value of global_variable_1 showed the changes, because it was accessed and changed by the local() function.

    Let’s take another example, but here we do not use the global keyword:

    var = 30    # global variable
    
    def local():
        var = 30    #local variable
        var = var +40
        print("var inside the local function",var)
    
    local()
    print("var outside the function", var)

    #Output:

    var inside the local function 70
    var outside the function 30

    Same example with global keyword

    var = 30    # global variable
    
    def local():
        global var   #global variable
        var =var+ 40
        print("var inside the local function ",var)
    
    local()
    print("var outside the function", var)

    #Output

    var inside the function local 70
    var outside the function 70

    Conclusion

    That sums up this Python tutorial on Python global local nonlocal variables. As you can see, the distinction between whether a Python variable is global, local, or nonlocal depends on its scope, i.e., where it can be used throughout the program.