OA. free
Free
MathWorks Core Computer Science Core Computer Science Medium

41.

MathWorks technical mcq question, verified with a worked answer. Free to practise - no sign-up.

(Python Question) For some code else**

What is the expected output?

for i in range(5):
    if i == 5:
        break
    else:
        print(i)
else:
    print("Here")

Pick ONE option

Choose one option.
Show answer & explanation
Answer: C. 0 1 2 3 4 Here

The loop iterates through range(5), which produces values 0–4. The condition i == 5 is never true, so the break statement never executes. In Python, a for-else block executes the else clause only when the loop completes normally (without a break). Since the loop completes naturally, both the loop prints (0 1 2 3 4) and the else clause prints (Here) are output.

Step-by-step Derivation:
Step-by-step execution:

  1. i=0: i != 5, so execute else block within the loop: print(0)
  2. i=1: i != 5, so execute else block within the loop: print(1)
  3. i=2: i != 5, so execute else block within the loop: print(2)
  4. i=3: i != 5, so execute else block within the loop: print(3)
  5. i=4: i != 5, so execute else block within the loop: print(4)
  6. Loop ends naturally (no break executed)
  7. Since loop completed without break, the for-else clause executes: print("Here")
    Final output: 0 1 2 3 4 Here