FOR vs WHILE: How to choose?

# junior import itertools for _ in itertools.count(): a = random.randrange(100) if a > 50: break print(a) text = "Hello World" i = 0 while i < len(text): print(text[i]) i += 1 # senior import random a = 0 while a < 50: print(a) a = random.randrange(100) text = "Hello World" for letter in text: print(letter)

When I began studying computer programming in C in my software engineering school, the use of for loops was forbidden. Using them would lead to receiving a grade of -42. The reason? To teach me the underlying logic of for loops with while loops. Now that I have the freedom to choose, when do I use for loops?

FOR vs WHILE: How to choose?

If you have the option to choose, this implies that it should be possible to use a for loop in situations where a while loop is used and a while loop in scenarios where a for loop was used. Let’s examine some examples.

Replace while loops with for loops

Let’s take a simple and usual while loop as an example:

import random

a = random.randint(0, 100)
while a < 10:
    print(a)
    a = random.randint(0, 100)

This while loop can be replaced with an infinite for loop if you put a break inside the body of the for:

import itertools
import random

for _ in itertools.count():
    a = random.randrange(100)
    if a > 50:
        break
        
    print(a)

What is itertools.count()? An infinite generator that will allows the loop to iterate for an unlimited amount of time. The for loop stops only because we “break” when the condition is met.

Replace for loops with while loops

You will take a typical for loop in python:

text = "Hello World"
for letter in text:
    print(letter)

You can replace the for loop with a while loop by creating an index and increasing it until you reach the length of the text.

text = "Hello World"
i = 0
while i < len(text):
    print(text[i])
    i += 1

Now you know how to change your while and for loops into the other kind.

The Rule of thumb

If you need to remember a rule that will help you most of the time, it’s this one:

Use For loops for known iteration number.

Use While loops for unknown iteration number.

Even if you can use both in almost any situation (I don’t have one where you can’t), this doesn’t mean that you should. Choose wisely. But be careful. Sometimes, we can “know” how many iteration would be required, but the code to actually determine that can be hard to read or understand. Don’t follow this rule if it lower readability and understanding of your code.

Leave a Reply

Discover more from The Way of Python

Subscribe now to keep reading and get access to the full archive.

Continue reading