Python – How to use a global variable in a function

In Python, we can use a global keyword to referring a global variable.

1. Review the below example :


a = 10

def updateGlobal():
    a = 5

updateGlobal()
print(a)  # 10

Output – It will return a 10, instead of 5.


10

2. To modify the global variable “a”, add a global keyword like this :


a = 10

def updateGlobal():
    global a
    a = 5

updateGlobal()
print(a)  # 5

Output


5

References

  1. Python docs – global

About the Author

author image
mkyong
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

avatar