0
0
Pythonprogramming~10 mins

Iteration using range() in Python - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Iteration using range()
Start: i = 0
Check: i < stop?
NoExit loop
Yes
Execute loop body
Update: i = i + 1
Back to Check
The loop starts with i at 0, checks if i is less than stop value, runs the loop body if yes, then increases i by 1 and repeats until the condition is false.
Execution Sample
Python
for i in range(3):
    print(i)
This code prints numbers 0, 1, and 2 by looping over range(3).
Execution Table
Iterationi valueCondition (i < 3)ActionOutput
10TruePrint i0
21TruePrint i1
32TruePrint i2
43FalseExit loop
💡 i reaches 3, condition 3 < 3 is False, loop ends
Variable Tracker
VariableStartAfter 1After 2After 3Final
i0 (initial)1233 (loop ends)
Key Moments - 3 Insights
Why does the loop stop when i equals 3?
Because the condition i < 3 becomes False at i = 3, so the loop exits as shown in execution_table row 4.
Does the loop include the stop value 3 in the output?
No, the loop runs while i is less than 3, so it stops before reaching 3, as seen in the outputs 0, 1, 2.
What happens if range(3) is changed to range(5)?
The loop will run 5 times with i from 0 to 4, increasing the number of rows in execution_table accordingly.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the value of i at iteration 2?
A0
B1
C2
D3
💡 Hint
Check the 'i value' column in execution_table row for iteration 2.
At which iteration does the condition become false and the loop stops?
A4
B3
C2
D1
💡 Hint
Look at the 'Condition' and 'Action' columns in execution_table to find when the loop exits.
If we change range(3) to range(2), how many times will the loop run?
A1 time
B3 times
C2 times
D0 times
💡 Hint
Refer to variable_tracker to see how i changes with different range values.
Concept Snapshot
for i in range(stop):
    # loop body

- i starts at 0
- runs while i < stop
- increments i by 1 each loop
- stop value is NOT included
- prints 0 to stop-1
Full Transcript
This visual trace shows how a for loop with range(stop) works in Python. The loop starts with i at 0 and runs as long as i is less than the stop value. Each iteration prints the current i and then increases i by 1. When i reaches the stop value, the condition becomes false and the loop ends. The execution table tracks each iteration's i value, condition check, action, and output. The variable tracker shows how i changes step by step. Key moments clarify why the loop stops before reaching the stop value and what happens if the range changes. The quiz tests understanding of i values and loop stopping conditions.