How to Use Global Variable in Python
The following is the example telling us how to define and use global variable in python.
global cnt
cnt = 0
def addCnt():
global cnt
cnt += 1
print("cnt in addCnt= ", cnt)
def subCnt():
global cnt
cnt *= 4
print("cnt in subCnt = " + str(cnt))
def printCnt():
global cnt
print("cnt in printCnt= ", cnt)
if __name__ == '__main__':
#Global variables in main function don't need to add global key word.
cnt = 10
addCnt()
subCnt()
printCnt()
Note:
In main function, we don’t need to add global key word. otherwise, we will get a warning.
The following are some Python Usage Examples. You can access it to get more details.
Python Files and Directories Operation
Have a good day. Take care!
Share this article to your social media