0
0
Pythonprogramming~10 mins

While loop execution flow in Python - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - While loop execution flow
Initialize variable
Check condition
Execute loop body
Update variable
Back to Check condition
The while loop starts by initializing a variable, then checks a condition. If true, it runs the loop body, updates the variable, and repeats. If false, it exits.
Execution Sample
Python
i = 0
while i < 3:
    print(i)
    i += 1
This code prints numbers 0, 1, and 2 by looping while i is less than 3.
Execution Table
Stepi valueCondition (i < 3)ActionOutput
10TruePrint 0, i = i + 10
21TruePrint 1, i = i + 11
32TruePrint 2, i = i + 12
43FalseExit loop
💡 i reaches 3, condition 3 < 3 is False, loop stops
Variable Tracker
VariableStartAfter 1After 2After 3Final
i01233
Key Moments - 2 Insights
Why does the loop stop when i is 3 even though the code inside the loop updates i?
The condition i < 3 is checked before each loop iteration. When i becomes 3, the condition is False, so the loop exits before running the body again (see execution_table step 4).
What happens if we forget to update i inside the loop?
If i is not updated, the condition i < 3 stays True forever, causing an infinite loop. The execution_table shows i changing each step to avoid this.
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 value' column in execution_table row 3.
At which step does the condition become false and the loop stops?
AStep 2
BStep 3
CStep 4
DStep 1
💡 Hint
Look at the 'Condition' column in execution_table where it shows False.
If we change the condition to i < 5, how would the variable_tracker change?
Ai would stop at 3
Bi would go up to 5
Ci would stay at 0
Di would decrease
💡 Hint
Variable i increases each loop until condition is False; changing condition to i < 5 means i goes up to 5.
Concept Snapshot
while condition:
    # loop body

- Checks condition before each loop
- Runs body only if condition True
- Updates variables inside loop to avoid infinite loops
- Stops when condition becomes False
Full Transcript
This visual shows how a while loop works in Python. We start with a variable i set to 0. The loop checks if i is less than 3. If yes, it prints i and adds 1 to i. This repeats until i reaches 3. Then the condition is false and the loop stops. The execution table tracks each step, showing i's value, the condition check, the action taken, and output printed. The variable tracker shows how i changes after each loop. Key moments explain why the loop stops and what happens if we forget to update i. The quiz tests understanding of i's value at steps, when the loop ends, and effects of changing the condition.