# Tutorial 4 - Problem 5 1. variable1 = 1 2. variable2 = 2 3. def function1(): 4. variable3 = 3 5. variable4 = variable3 6. return variable4 7. def function2(parameter1): 8. variable5 = parameter1 9. variable6 = 6 10. return variable5 11. def function3(parameter2, parameter3): 12. variable7 = parameter2 13. variable8 = parameter3 14. return variable9 # main 15. variable10 = function2(variable3) 16. print(function3(variable5, variable2)) 17. variable1 = function1() # a. What is wrong with it? # NameError: name 'variable3' is not defined in statement variable10 = function2(variable3) # NameError: name 'variable5' is not defined in statement print(function3(variable5, variable2)) # NameError: name 'variable9' is not defined in statement return variable9 in function3() # b. In general, what is the scope of a variable? # The section of the program over which the variable is known and can be used. # c. In general, what is the scope of a parameter? # A parameter is a variable, so its scope, usually, is over the body of the function for which it is a parameter. # d. In general, what is the relationship between variable scope and the stack frame of a function? # Variables local to a function (and parameters) are given memory location in the stack frame # assigned to a fucntion when it is executed. # When the execution flow returns from the function to the "caller" of the function, the stack frame # is recycled, i.e., the variables are no longer accessible, they do no have "scope" anymore. # e. What is the scope of each of the 10 variables in the Python program? # Scope of variable1 and variable2 is the whole program. # Scope of variable3 is lines 4., 5. and 6. # Scope of variable4 is lines 5. and 6. # Scope of variable5 is lines 8., 9. and 10. # Scope of variable6 is lines 9. and 10. # Scope of variable7 is lines 12., 13. and 14. # Scope of variable8 is lines 13. and 14. # Variable9 is problematic (not yet defined) and has no scope. # Scope of variable10 is lines 15., 16. and 17. # f. What is the scope of each of the 3 parameters in the Python program? # Scope of parameter1 is the body of function2, i.e., parameter1 is known over the whole body of function2. # SCope of parameter2 and parameter3 is the body of function3, i.e., parameter2 # and parameter3 are known over the whole body of function3.