Skip to content

Question 8

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

if True:
    x = 30
    if x < 100:
        x += 2
    elif x == 100:
        x += 1
    else:
        x -= 2
else:
    x = 15
print(x)
Solution

The program starts with either if True or else. Between the two, the program flow will always enter if True - look back at how a different if-else block works like this one below; it is understood that the program flow enters the if block if the condition tied to it is satisfied.

if x > 10:      # enter this block if `x > 10` is True
    print(x)
else:
    print('0')

With if True, the condition tied to it is simply True, which, in other words, just evaluate to True on default. Hence, we now enter into this block.

Going in, a variable x is declared and defined with value 30. The program flow now encounters another set of if-else branches.

  • x < 100: True \(\Rightarrow\) enter this if block
  • ignore if branch x == 100 and else

From inside the x < 100 branch, carry out x += 2, which effectively adds 2 to the existing value of x: 30 + 2 = 32.

Finally, the value of x output is just 32.

Answer
32