Step-by-Step Execution:
-
Initialization:
i = 0The variable i starts with value 0.
-
First iteration:
-
Condition i < 3 → 0 < 3 ✅ True
-
Check if i == 1 → 0 == 1 ❌ False
-
Execute print(i) → prints 0
-
Execute i += 1 → now i = 1
-
-
Second iteration:
-
Condition i < 3 → 1 < 3 ✅ True
-
Check if i == 1 → 1 == 1 ✅ True
break is executed → loop immediately stops
-
-
Else block:
else:
print("Done")The else part of a while loop runs only if the loop finishes normally
— that is, without encountering a break.But since a break was used, the else block is skipped.
Final Output:
0
Key Concept:
In Python, a while loop’s else executes only when the loop ends naturally (i.e., the condition becomes false).
If the loop ends because of a break, the else part is not executed.


0 Comments:
Post a Comment