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
A simple example code won’t assign the new value to a local variable and not change the value of the global variable. The ‘global’ keywords hide the local variable with the same name, so as 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)
func()
print('Total = ', total)
Output:
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 or suggestions on this Python variable tutorial.
Note: IDE: PyCharm 2021.3.3 (Community Edition)
Windows 10
Python 3.10.1
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.