Skip to content

Question 7

What is the output of the following code? [3 marks]

1
2
3
4
5
6
7
x = 15 / 5
if x > 5:
    print(x - 1)
elif x > 4:
    print(x - 2)
else:
    print(x)
Solution

The value of x is evaluated from the math operation 15 / 5. This results in 3.0.

Note

x does not take on the integer value 3; we can get integer 3 only from integer division //.

This is then followed by an if-else branch. We now trace the working of the code as follows:

  • x > 5: False \(\Rightarrow\) skip this if block
  • x > 4: False \(\Rightarrow\) skip this elif block
  • \(\Rightarrow\) Enter else block

Inside the else block, we only print out the value of x, that being 3.0.

Answer
3.0