Question 26 (our toss-up question)
What is the output of the following code?
Hint
Begin with n = 10.
Starting from foo(12, 24), you enter foo() where it has a local n = 100, which means you can begin ignoring the global instance of n.
You'll end up with invoking either one of the two bar() function calls.
In that bar() function call, you now pick between the results of x / y or x - y.
What would n be here in this case?
Solution
Begin with n = 10; this is considered a global variable n, which will be as such in every function called after unless a local n value is defined.
foo() is only invoked once and at this point, defining local variables x = 12 and y = 24.
foo() has a local variable n, so within the scope of this function, n = 100 and not n = 10.
This causes the Boolean expression in the if statement to be False, i.e., x > n \(\Rightarrow\) 12 > 100 is False.
Hence, you return the returned output of bar(y, x), i.e., bar(24, 12).
Inside the bar() call, x = 24 and y = 12.
Also, no n is defined - here, we default to the global n value, i.e., n = 10.
Because of this, x > n \(\Rightarrow\) 24 > 10 is True.
Hence, return the result of x / y, i.e., 24 / 12 = 2.0.
Note that the output is 2.0 and not 2; this is because the single slash division operator (i.e., /) produces a float result, whilst the double slash division operator (i.e., //) produces an int result, only containing the integer quotient from the division operation.
For example, 20 / 8 = 2.5, whilst 20 // 8 = 2.