In Python, when a variable is defined within a function, it is considered a local variable and is only accessible within that function. However, if a variable is defined outside of any function, it is considered a global variable and is accessible throughout the entire program. When a function modifies a global variable, it creates a new local variable with the same name, which shadows the global variable. This local variable exists only within the scope of the function and is separate from the global variable. To modify the global variable, you have to use the global keyword to specify that you are referring to the global variable, not the local one. The reason for this behavior is to prevent accidental modification of global variables. By default, a function can only read the value of a global variable, not modify it. This ensures that the function does not accidentally change the value of a global variable that might be used in other parts of the program. Using the global keyword explicitly indicates that the developer intends to modify the global variable and makes it clear that the change will have an effect outside the scope of the function.
to modify the global variables you can do following
a = 0
def func():
global a
a+=2
func()
print(a) # should print 2