Python change global variable in function | Example code

Use global keywords to access and change global variables in function in Python.

Note: No need for global for mutable objects, if you’re modifying them in place.

Python change global variable example

Simple example code won’t assign the new value to a local variable and not changing the value of the global variable. The ‘global’ keywords hide the local variable with the same name, so to access both the local & global variable inside a function.

total = 100

def func():
    # refer to global variable 'total' in function
    global total
    if total > 10:
        total = 15

print('Total = ', total)
print('Total = ', total)


Python change global variable in function

Another way is to use the global() function it returns a dictionary of elements in the current module and we can use it to access / modify the global variable without using the ‘global’ keyword i,e.

Do comment if you have any doubts and suggestions on this Python variable tutorial.

Note: IDE: PyCharm 2021.1.3 (Community Edition)

Windows 10

Python 3.7

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.