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