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

mkyong

Founder of Mkyong.com, passionate Java and open-source technologies. If you enjoy my tutorials, consider making a donation to these charities.

0 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments