Opening Hours :7AM to 9PM
In this tutorial, you’ll learn about Python Global variables, Local variables, Nonlocal variables and where to use them.
Example 1: Create a Global Variable x = "global" def myfun(): print("x inside:", x) myfun() print("x outside:", x) Output x inside: global x outside: globalIn the above code, we created x as a global variable and defined a myfun() to print the global variable x. Finally, we call the myfun() which will print the value of x.
x = 10 def myfun(): x = x * 2 print(x) myfun() Output UnboundLocalError: local variable 'x' referenced before assignmentThe Output shows an error because Python treats x as a local variable and x is also not defined inside myfun().
Example 2: Accessing local variable outside the scope def myfun(): y = 10 print(y) myfun() print(y) Output NameError: name 'y' is not definedThe Output shows an error because we are trying to access a local variable y in a global scope whereas the local variable only works inside myfun() or local scope.
Example 3: Create a Local Variable Normally, we declare a variable inside the function to create a local variable. def myfun(): y = 10 print(y) myfun() Output localLet's take a look at the earlier problem where x was a global variable and we wanted to modify x inside myfun().
Example 4: Using Global and Local variables in the same code x = 10 def myfun(): global x y = 20 x=x+10 print(x) print(y) myfun() Output global global localIn the above code, we declare x as a global and y as a local variable in the myfun(). Then, we use multiplication operator * to modify the global variable x and we print both x and y.
Example 5: Global variable and Local variable with same name x = 5 def myfun(): x = 10 print("local x:", x) myfun() print("global x:", x) Output local x: 10 global x: 5In the above code, we used the same name x for both global variable and local variable. We get a different result when we print the same variable because the variable is declared in both scopes, i.e. the local scope inside myfun() and global scope outside myfun().
Example 6: Create a nonlocal variable def outer(): x = "local" def inner(): nonlocal x x = "nonlocal" print("inner:", x) inner() print("outer:", x) outer() Output inner: nonlocal outer: nonlocalIn the above code, there is a nested inner() function. We use nonlocal keywords to create a nonlocal variable. The inner() function is defined in the scope of another function outer().