Practice question · Select all that apply
The counter starts at i = 0. Select every loop below that runs its body exactly 5 times.
Hints
- Count the values each loop actually visits, watching the < versus <= boundary.
- range(1, 6) stops before 6, and while i <= 5 runs one pass more than while i < 5.
Show the answer
- A. for i in range(1, 6)
- B. while i < 5 (with i = i + 1 each pass)
- E. for i in range(5)
Why
range(5) gives 0..4 and while i < 5 from 0 gives 0..4, both 5 passes; range(1, 6) gives 1..5, also 5. But while i <= 5 runs 0..5, which is 6 passes, and while i < 4 runs 0..3, only 4. The <= versus < boundary is the exact off-by-one to watch.
Practise Loops and Repeated Computation
The app has 6 more questions on this lesson, and keeps your place in the course. Computer Science I is free to start.
More questions on Loops and Repeated Computation
- Order the parts of a correct while loop so that it counts up and then stops.
- Match each loop keyword or form to what it does.
- Modifying a list while looping over it can silently skip elements. Why does removing an item mid-iteration…
- An off-by-one error in a loop boundary usually causes a crash, which is what makes it easy to find.