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) #function calling add() print("In main:", c)
When we run above program, the output will be:
output:
Inside add(): 2
In main: 2
In the above program, we define c as a global keyword inside the add() function.
Then, we increment the variable c by 1, i.e c = c + 2. After that, we call the add()function. Finally, we print global variable c.
As we can see, change also occurred on the global variable outside the function, c = 2.
Example 4 :
Share a global Variable Across Python Modules
Create a config.py file, to store global variables
FileName: config.py
a = 0
b = “empty”
Create a update.py file, to change global variables
FileName: update.py
import config
config.a = 10
config.b = “alphabet”
Create a main.py file, to test changes in value
FileName: main.py
import config
import update
print(config.a)
print(config.b)
#Filename: config.py a = 0 b = "empty"
#FileName: update.py import config config.a = 10 config.b = "alphabet"
#FileName: main.py import config import update print(config.a) print(config.b)
When we run the main.py file, the output will be
10
alphabet
In the above, we create three files:
config.py,
update.py and
main.py.
* The module config.py stores global variables of a and b.
* In update.py file, we import the config.py module and modify the values of a and b.
* Similarly, in main.py file we import both config.py and update.py module.
* Finally, we print and test the values of global variables whether they are changed or not.