While or For? Which one to choose?

In the previous few lessons, you’ve been exposed to both while loops and for loops. Though there are some important differences, both of these programming features can be used to accomplish the same basic task: Repeat code some number of times. This leads to some questions such as:

The answer to (A) is multi-faceted. In part, both exist due to historical reasons. Many other programming languages that came before python have included both types of loops. Other very popular (and older) languages such as C and Java, have both of these features. Thus, for the sake of making this familiar to programmers, Python has included both.

However, this is not the only reason they both exist. Though they both allow the user to repeat code, they both do so in different ways.

With while-loops, the repetition is based on checking a condition. A while loop can be thought of as a repeating if-statement. There are times where logically, it makes more sense to use a while-loop. On the other hand, a for-loop is used to iterate through sequences. In a previous lesson, you say an example of a for-loop iterating through a specified range of values. For loops can also be used for iterating through the characters of a string (which you’ll see in the next lesson) or through the elements of a list (which you’ll see in a much later lesson).

As for the answer to (B), each kind of loop has its unique pros and cons. As you become a more experienced programmer, you’ll start to get a feel for when one is a more reasonable choice than the other. You’ll see many examples throughout the rest of the lessons in this book of both while loops and for loops.

The answer to (C) is “no.” It really just depends on the context.



PyFlo Home Complete Bookmark Next