Skip to content

Question 12

What is the output of the following code?

def foo(p):
    (x, y) = p
    if x > 0 and y > 0:
        return True
    elif x > 0 or y > 0:
        return x*y > 0
    elif x < 0:
        return True
    print(p)
    return None

p1, p2, p3 = (4,-4), (0,0), (-4,-4)
print(foo(p1), foo(p2), foo(p3))
Solution

foo(p1)

Given p1 = (4,-4), in foo(), x = 4, y = -4.

  • x > 0 and y > 0: True and False \(\Rightarrow\) False
  • x > 0 or y > 0: True or False \(\Rightarrow\) False, hence foo(p1) returns False.

foo(p2)

Given p2 = (0,0), in foo(), x = 0, y = 0.

  • x > 0 and y > 0: False and False \(\Rightarrow\) False
  • x > 0 or y > 0: False or False \(\Rightarrow\) False
  • x < 0: False

We approach print(p), where you print out (0,0) as the value passed into argument p before returning None from foo(). What this means for the output is that (0, 0) will be printed here immediately.

(0, 0)
# formulating print(foo(p1), foo(p2), foo(p3)), since it's trying to get all the returned values from each foo() call before printing it out

foo(p3)

Given p3 = (4,-4), in foo(), x = -4, y = -4.

  • x > 0 and y > 0: False and False \(\Rightarrow\) False
  • x > 0 or y > 0: False or False \(\Rightarrow\) False
  • x < 0: True, hence foo(p3) returns True.

With foo(p1), foo(p2) and foo(p3) returning False, None and True respectively, the print statement at the end prints them with space characters in between.

Answer
(0, 0)
False None True