0
0
Pythonprogramming~10 mins

While–else behavior in Python - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - While–else behavior
Start: Initialize condition
Check condition
Execute body
Update condition
Back to Check condition
The while loop runs as long as the condition is true. If it ends normally (condition false), the else block runs. If the loop exits early (break), else is skipped.
Execution Sample
Python
i = 0
while i < 3:
    print(i)
    i += 1
else:
    print('Done')
Counts from 0 to 2, then prints 'Done' after the loop finishes normally.
Execution Table
StepiCondition (i < 3)ActionOutput
10TruePrint 0, i = i + 10
21TruePrint 1, i = i + 11
32TruePrint 2, i = i + 12
43FalseExit loop, run elseDone
5--End-
💡 i reaches 3, condition 3 < 3 is False, loop ends normally, else block runs
Variable Tracker
VariableStartAfter 1After 2After 3Final
i01233
Key Moments - 2 Insights
Why does the else block run after the while loop?
Because the loop ended normally when the condition became False (see execution_table step 4). The else runs only if no break interrupts the loop.
What happens if we add a break inside the loop?
If break runs, the loop exits immediately and the else block does NOT run. This is because else runs only on normal loop completion.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the value of i at step 3?
A2
B3
C1
D0
💡 Hint
Check the 'i' column at step 3 in the execution_table.
At which step does the condition become False and the else block runs?
AStep 2
BStep 4
CStep 3
DStep 5
💡 Hint
Look at the 'Condition' and 'Action' columns in execution_table for when condition is False and else runs.
If we add 'if i == 1: break' inside the loop, what happens to the else block?
AIt runs before the loop
BIt runs after the loop
CIt does not run
DIt runs twice
💡 Hint
Recall key_moments about break skipping the else block.
Concept Snapshot
while condition:
    # loop body
else:
    # runs if loop ends normally (no break)

- else runs only if while condition becomes False
- else skipped if break exits loop early
- useful for post-loop actions when no early exit
Full Transcript
This visual trace shows how a while loop with an else block works in Python. The loop runs while the condition is true, updating variable i each time. When i reaches 3, the condition becomes false, so the loop ends normally and the else block runs, printing 'Done'. If the loop had a break statement, the else block would not run. The variable tracker shows how i changes each step. The key moments clarify why else runs only on normal loop completion. The quiz questions help check understanding of the loop steps and else behavior.