Opening Hours :7AM to 9PM
In this article, you’ll learn about the global keyword, global variable and when to use global keywords.
Before reading this article, make sure you have got some basics of Python Global, Local and Nonlocal Variables.
c = 1 # global variable def add(): print(c) add() When we run the above program, the output will be: 1However, we may have some scenarios where we need to modify the global variable from inside a function.
Example 2: Modifying Global Variable From Inside the Function c = 1 # global variable def add(): c = c + 2 # increment c by 2 print(c) add() When we run the above program, the output shows an error: UnboundLocalError: local variable 'c' referenced before assignment This is because we can only access the global variable but cannot modify it from inside the function. The solution for this is to use the global keyword.Example 3: Changing Global Variable From Inside a Function using global
c = 0 # global variable def add(): global c c = c + 2 # increment by 2 print("Inside add():", c) add() print("In main:", c) When we run the above program, the output will be: Inside add(): 2 In main: 2In the above program, we define c as a global keyword inside the add() function.
Create a config.py file, to store global variables a = 0 b = "empty" Create a update.py file, to change global variables import config config.a = 10 config.b = "alphabet" Create a main.py file, to test changes in value import config import update print(config.a) print(config.b) When we run the main.py file, the output will be 10 alphabetIn the above, we have created three files: config.py, update.py, and main.py.
def myfun(): x = 20 def myfuninner(): global x x = 25 print("Before calling myfuninner: ", x) print("Calling myfuninner now") myfuninner() print("After calling myfuninner: ", x) myfun() print("x in main: ", x) The output is : Before calling myfuninner: 20 Calling myfuninner now After calling myfuninner: 20 x in main: 25In the above program, we declared a global variable inside the nested function myfuninner(). Inside myfun() function, x has no effect of the global keyword.