When to use what type of repetition in a program

                                                                                                                      @PablO_CVi

The for statement iterates through a collection or iterable object or generator function.

The while statement simply loops until a condition is False.

It isn’t preference. It’s a question of what your data structures are.

Often, we represent the values we want to process as a range (an actual list), or xrange (which generates the values). This gives us a data structure tailor-made for the for statement.

Generally, however, we have a ready-made collection: a set, tuple, list, map or even a string is already an iterable collection, so we simply use a for loop.

In a few cases, we might want some functional-programming processing done for us, in which case we can apply that transformation as part of iteration. The sorted and enumerate functions apply a transformation on an iterable that fits naturally with the for statement.

 

If you don’t have a tidy data structure to iterate through, or you don’t have a generator function that drives your processing, you must use while.

 

 

CC BY 4.0 When to use what type of repetition in a program by Pablo is licensed under a Creative Commons Attribution 4.0 International License.

Comments are closed.