# File: scope.py # Program to demonstrate how functions handle variables # This version focuses on variable scope *only* # # Matt Bishop, COSMOS 2012, Cluster 4 # # # let's define something for main # k = 1 # # this function has k as a local variable # changes do not affect the value of k in main # def func1(): k = 2 print("In func1, k's value is", k) # # this function refers to the k defined at the top # of the file (that is, main's k) # the "global k" makes this happen # changes here do affect the value of k in main # def func2(): global k k = 3 print("In func2, k's value is", k) # # this function refers to the k in the parameter list # so, in effect, k is a local variable # changes do not affect the value of k in main # (note: # def func3(k): print("As an argument to func3, the parameter k's value is", k) k = 4 print("In func3, k's value is", k) # # now for the main routine # the k here refers to the one at the top of the file # print("Initially, k's value is", k) # # func1() will not change k's value # func1() print("After func1, k's value is", k) # # func2() *will* change k's value # func2() print("After func2, k's value is", k) # # for clarity, now reset it to the initial value # k = 1 print("After reassignment, k's value is", k) # # func3() will not change k's value # func3(k) print("After func3, k's value is", k)