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

No comments yet. Be the first to leave a comment!

Leave a Comment

Your email address will not be published. Required fields are marked *