# File: scope.py # Program to show how scope works with functions # # General rule: LEGB # -- first, look for names assigned in any way in the local function (def) # and *not* declared global # -- next, look for local names in enclosing function definitions going # from innermost to outermost # -- third, look for names assigned at the top level of the module (globals) # -- fourth, look for names pre-assigned in buit-in names modules (like # open, range, SyntaxError, etc.) # # Matt Bishop, ECS 36A, Winter 2019 # # a global variable # globbie = 1234 # # first, a function that defines a local variable "globbie" # note there is no "global" line # def func1(): globbie = 16 return globbie # # now, a function that sets the value of the global variable "globbie" # note the "global" line # def func2(): global globbie globbie = 18 return globbie # # now, a function that defines a parameter "globbie" # note there is no "global" line # note: without the parameter, this gives an error # def func3(globbie): globbie = globbie + 1 return globbie # # now we're going to nest functions # here, the outer one changes a local globbie # and the inner one changes the global globbie # def func4(): globbie = 10 y = func2() return y # # again we're going to nest functions # here, the inner one references the global globbie, # not the one defined in the outer function # def func5a(): y = globbie + 22 return y def func5(): globbie = 10 z = func5a() return z # # now we're going to nest function *definitions* # here, the inner one references the globbie defined # in the outer function, not the global one # def func6(): def func6a(): y = globbie + 975 return y globbie = 22 z = func6a() return z # # pulling it all together # x = func1() print("globbie =", globbie, "func1() returned =", x) x = func2() print("globbie =", globbie, "func2() returned =", x) x = func3(5678) print("globbie =", globbie, "func3() returned =", x) globbie = 3456; print("globbie =", globbie) x = func4() print("globbie =", globbie, "func4() returned =", x) x = func5() print("globbie =", globbie, "func5() returned =", x) x = func6() print("globbie =", globbie, "func6() returned =", x)