I've been trying to understand the behaviour of global
variables in Python. From here, I gather that I can read any variable defined in an outer scope. If I want to modify it in an inner scope, I have to "declare" as global
in that inner scope, so that Python looks for it according to its scoping rules and knows I'm not creating a new local variable.
But why does the following correctly print the values of variables a
and b
?
import sys
def func1():
print a # will print 1
print b # will print 2
return
def main():
global a
a = 1
global b
b = 2
func1()
return 0
if __name__ == '__main__':
status = main()
sys.exit(status)