Consider this Python code: Line # Code 1 def func (a): 2 # line 2 3 a = 1 4 # li
ID: 3626958 • Letter: C
Question
Consider this Python code:Line # Code
1 def func (a):
2 # line 2
3 a = 1
4 # line 4
5 a = func2 (a,a)
6 # line 6
7 def func2(a,b):
8 # line 8
9 b = a+1
10 return b
11 a = 6
12 # line 12
13 func (a)
14 # line 14
List the line numbers in the order they are executed. (You can ignore the blank lines and def lines.)
What is the value of a when line 6 is executed? (i.e. when line 6 actually runs, not when it is first seen by the interpreter)
What is the value of b when line 14 is executed?
Is the value of a on line 14 different from the value of a on line 12? Explain.
Explanation / Answer
In python, indentation is significant. Indentation of lines determines the block structure of the code. As such, I've taken a stab at indenting your code properly:
I hope this is correct. At least, when I tried any other indentation, the python interpreter yelled at me. So, on to the analysis.
Lines one through six consist of the definition of a function. Lines seven through ten also consist of the definition of a function. As such, the order of execution will be:
Note that I don't count lines 2, 4, 6, 8, 12, or 14 in the execution. This is because these lines are comments, and are ignored by the interpreter.
The rest of the question is nonsensical. Lines 6, 14, and 12 are never executed, because they are comment lines. I assume, however, that the question means more along the lines of “if there were a print statement on line <whatever>, what would…” Also, there is ambiguity insofar as the variable a is concerned, as it exists in several scopes. I'll see what we can do about sensible answers, then.
On line six, the local variable a hides the global variable (declared and defined on line 11). The value of this variable at this point is 2, as this is after func2 has executed and returned its result.
On line fourteen, b does not exist. b exists only within the scope of func2, and python issues a NameError if we try to access b at that point.
The value of a is unchanged between lines twelve and fourteen. This is because
Understanding all of this requires an understanding of scope, passing by value, and returning a value. Python is a cheap language to play with—all you need is a text editor and a python interpreter, easily obtainable from the internet. I encourage that you take the time to download and install python if your instructor is using it extensively.