Choosing Between For and While Loops

Choose iteration over known inputs when each supplied item has work. Use a condition-driven loop when the state determines whether another step is needed.

Source
Anbloq
Language
English
Created
Updated
Chapters
4
Reading time
2 min
In this article4 chapters
  1. Read the stopping rule
  2. Try the empty start
  3. Choose whose state determines whether another step exists
  4. Consider zero and one ordinary iterations first

Read the stopping rule

A Python for loop over three names performs one step for each supplied name. A while loop trying a value until a target is reached needs a condition and an update that eventually makes it false. This leads to termination measures.

Try the empty start

When there are zero names, a for loop over the empty collection does nothing. When the target is reached before a while loop, its body also does nothing. A boundary test in each case verifies that initialization and output still happen where intended.[1]

Choose whose state determines whether another step exists

A known sequence of measurements gives one input per step until exhausted. A for loop can let the iterator supply those values directly. A search monitoring an evolving numeric interval may need to repeat while the interval still contains candidates. In that case the while condition describes valid state and the body's update must shrink or move the interval. Termination measures helps make the intended progress explicit.

Consider zero and one ordinary iterations first

A while loop such as “while remaining is positive” with a starting count zero never enters its body. A for loop over no items has the same number of body executions. Neither case performs initialization or cleanup placed only inside the body. Decide which steps need to occur outside it.

Try a collection with one item and a state-driven loop beginning one unit from its stopping bound. Determine how many times the condition is checked and how many updates actually run. If the body can skip an update through a continue, check whether another path still makes progress. See loop progress conditions for the reasoning behind termination.

References

  1. Python Software Foundation, Python Tutorial: Control Flow ↩