nerdexam
Python_Institute

PCEP-30-02 · Question #342

What is the expected output of the following code? equals = 0 for i in range(2): for j in range(2): if i == j: equals += 1 else: equals += 1 print(equals)

The correct answer is B. 3. Option B is correct because this code uses Python's for-else construct - the else block is aligned with the outer for i loop, meaning it executes once after that loop finishes normally. The inner if i == j increments equals only when i and j are equal, which happens twice: at…

Question

What is the expected output of the following code? equals = 0 for i in range(2): for j in range(2): if i == j: equals += 1 else: equals += 1 print(equals)

Options

  • A1
  • B3
  • C4
  • DThe code outputs nothing.

How the community answered

(26 responses)
  • A
    8% (2)
  • B
    73% (19)
  • C
    4% (1)
  • D
    15% (4)

Explanation

Option B is correct because this code uses Python's for-else construct - the else block is aligned with the outer for i loop, meaning it executes once after that loop finishes normally. The inner if i == j increments equals only when i and j are equal, which happens twice: at (i=0, j=0) and (i=1, j=1), giving equals = 2. Then the outer loop's else fires once more, making the final value 3.

Why the distractors are wrong: A (1) would only be correct if the loop stopped after the first match - it doesn't. C (4) is a common trap if you misread else as belonging to the if statement (where both branches always increment, yielding 4 iterations × 1 = 4); the indentation is what changes everything. D is wrong because print(equals) is unconditionally called after the loops.

Memory tip: When you see else paired with a for or while loop in Python, it does not mean "if the condition was false." It means "run this block once after the loop completes without hitting a break." Think of it as the loop's "completion bonus" - it fires once, not once per iteration.

Community Discussion

No community discussion yet for this question.

Full PCEP-30-02 Practice