#------------------------------------------------------------------------------ # Scope.py # # The scope of a variable is the area of the program where it can be accessed, # i.e. read from or written to. # # The three different different x's in different parts of the program represent # different areas of memory, i.e. there are 3 different variables all with the # name x. The one in main is called the 'global' variable x. # # In Python, functions cannot write to global variables, by say assigning a # value to them. A function can read from a global variable though, for instance # by printing it. In general, your functions should not interact with global # variables in any way, since it can make the job of tracing your program very # complex, leading to confusion and errors. # #------------------------------------------------------------------------------ # Try putting x = 8 here, you'll find no difference. Thus, the "main program" # is really everything outside of all functions. def fcn1(): x = 6 # A local variable called x, different from that in fcn2() and print(x) # in the "main program". It's scope is fcn1() only. # end fcn1() def fcn2(): x = 7 # Another local variable called x. Try commenting this line out. print(x) # Then there is no local x, and so the global x is printed. # end fcn2() #------------------------------------------------------------------------------ # no function main(), so this is global scope x = 8 # Another variable called x in the global scope, i.e outside # of all functions. print(x) fcn1() print(x) fcn2() print(x)