If you want to refer to a global variable in a function you have to use the “global” keyword:
Ex-
gvar=1
#you need to refer to global to modify the value
def set_gvar():
global gvar
gvar = 2
#no need to declare global to read value
def print_gvar():
print(gvar)
set_gvar()
print_glvar()
# prints 2
The main reason for using the “global “ keyword is to make Python sure that you know what you are dealing with and not mistaking it with a local variable. If “global” keyword is not mentioned, Python will implicitly declare it as local.
Hope this answer helps!