nerdexam
Python_Institute

PCEP-30-02 · Question #341

What happens when the user runs the following code? total = 0 for i in range(4): if 2 * i < 4: total += 1 else: total += 1 print(total)

The correct answer is C. The code outputs 2. Option C is correct because the condition 2 i < 4 is True for exactly two iterations: when i = 0 (gives 0 < 4) and i = 1 (gives 2 < 4). For i = 2, the expression equals 4, which is not less than 4, and i = 3 gives 6, also failing the condition - so only the two True iterations…

Question

What happens when the user runs the following code? total = 0 for i in range(4): if 2 * i < 4: total += 1 else: total += 1 print(total)

Options

  • AThe code outputs 1.
  • BThe code enters an infinite loop.
  • CThe code outputs 2.
  • DThe code outputs 3.

How the community answered

(49 responses)
  • A
    4% (2)
  • B
    6% (3)
  • C
    76% (37)
  • D
    14% (7)

Explanation

Option C is correct because the condition 2 * i < 4 is True for exactly two iterations: when i = 0 (gives 0 < 4) and i = 1 (gives 2 < 4). For i = 2, the expression equals 4, which is not less than 4, and i = 3 gives 6, also failing the condition - so only the two True iterations increment total, yielding total = 2.

A (outputs 1) is wrong because the condition holds for two iterations, not one. B (infinite loop) is wrong because range(4) is a finite sequence - the loop always terminates after exactly 4 iterations. D (outputs 3) is wrong because students often miscount: they may think 4 < 4 is true, or confuse < with <= - if the condition were 2 * i <= 4, then i = 2 would also pass, giving 3.

Memory tip: When you see 2 * i < 4, mentally solve for i < 2, which immediately tells you only i = 0 and i = 1 pass - no need to test all four values by hand. Remembering to treat < as strictly less than (never equal) prevents the off-by-one mistake that leads to choosing D.

Community Discussion

No community discussion yet for this question.

Full PCEP-30-02 Practice