livepython.net
CHAPTER 11While Loops
11.4  WHILE OR FOR

while Loop vs for Loop in Python: Which to Use?

for or while: Which Loop Should You Use?

Python has two loops, and many jobs can be done with either one. The rule of thumb: use for when you know what to go through, and while when you know when to stop.

Here is the same job, printing 1 to 3, both ways:

PYTHONedit me
for n in range(1, 4):
    print(n)
OUTPUT
1
2
3
PYTHONedit me
n = 1
while n <= 3:
    print(n)
    n += 1
OUTPUT
1
2
3

The for loop does the start, the check and the change for you, in one line. It can't forget the change, so it can't run forever by mistake. For this job, for wins.

Think of a teacher handing back tests: going through a known pile of papers is a for job. Waiting at the door until the last student arrives is a while job.

Pick the loop

The jobLoopWhy
go through every item of a list or stringforthe items are known
repeat exactly 10 timesfor with range(10)the count is known
ask until the answer is validwhileyou can't know how many tries
read until the user types donewhilethe end depends on the user
double until over 100whilethe number of rounds is unknown
count the digits of a numberwhilestop when nothing is left

A quick test

Ask yourself: "Before the loop starts, do I know how many rounds it will run, or which items it goes through?"

  • Yes → for.
  • No, I only know when to stop → while.

Common beginner doubt: "Is while the worse loop, then?" Not at all. It's the only one of the two that can wait for the user, or keep going until a goal is reached. Each loop is best at its own job.

for: you know what to go through. while: you know when to stop.

your turnPick the right idea

A program asks for a password until it's right. Which loop fits best?

Think about it, then pick one.
your turnPredict the output

What will this print?

n = 10 while n > 1: n = n // 2 print(n)
Your turn! What will this code show on the screen?

break and continue in a while Loop

You met break and continue in the for loops chapter. They work in a while loop too: break leaves the loop at once, and continue skips the rest of this round and goes back to the check.

PYTHONedit me
n = 0
while n < 6:
    n += 1
    if n % 2 == 0:
        continue
    print(n)
OUTPUT
1
3
5

For even numbers, continue skips the print() and jumps back to while n < 6:. Odd numbers reach the print().

Think of reading a book: continue is skipping a boring page and going on with the next one. break is closing the book.

The continue trap

In a for loop, continue is safe: the loop moves to the next item by itself. In a while loop, you do the change. If continue jumps over it, the variable never changes again:

n = 0
while n < 6:
    if n % 2 == 0:
        continue      # jumps back with n still 0
    print(n)
    n += 1            # never reached: an infinite loop

n is 0, continue jumps back, n is still 0, and so on forever.

The fix: change first

Put the change at the top of the round, before any continue, as in the first example. Then every round moves the loop on, whatever happens below.

breakcontinue
what it doesends the loopstarts the next round
where Python goesthe first line after the loopback to the while check
watch outmake sure it's reacheddon't skip the change

In a while loop, change the variable before any continue.

your turnFill the gap

Skip 3, print the rest

n = 0 while n < 5: n += 1 if n == 3: ? print(n)

It should print: 1 2 4 5

Which piece makes this code work?
your turnType the output

Type what this prints

n = 0 while n < 10: n += 1 if n == 4: break print(n)
Read the code line by line, then type the output exactly.

Using a while Loop with a List

A while loop can work through a list while it changes, for example taking items out until the list is empty. A list with items counts as true, and an empty list [] counts as false, just like an empty string in chapter 8.

PYTHONedit me
tasks = ["wash", "cook", "shop"]
while tasks:
    task = tasks.pop(0)
    print("Doing:", task)
print("All done!")
OUTPUT
Doing: wash
Doing: cook
Doing: shop
All done!

while tasks: reads as "while there are tasks left". Each round, pop(0) (chapter 9) takes the first item out of the list. After three rounds the list is empty, and the loop stops.

Think of a to-do pile on your desk: you take the top sheet, do it, and stop when the pile is gone.

Front or back?

  • tasks.pop(0) takes the first item: first in, first out, like a queue at a shop.
  • tasks.pop() takes the last item: last in, first out, like a stack of plates.

Going through by position

You can also walk through a list by its index, with a counter. This is what a for loop does for you:

PYTHONedit me
names = ["Sunny", "Rocky", "Lucky"]
i = 0
while i < len(names):
    print(i, names[i])
    i += 1
OUTPUT
0 Sunny
1 Rocky
2 Lucky

The check is i < len(names), not <=: the last index is one less than the length. Use <=, and the last round asks for names[3], which doesn't exist. That's an off-by-one error with a real error message:

PYTHONedit me
names = ["Sunny", "Rocky", "Lucky"]
i = 0
while i <= len(names):
    print(names[i])
    i += 1
OUTPUT
Sunny
Rocky
Lucky
IndexError: list index out of range

For plain "go through every item", for name in names: is shorter and safer. Use while when the list changes as you go, or when you stop early for a reason that depends on the items.

while my_list: keeps going until the list is empty.

your turnPredict the output

What will this print?

stack = [1, 2, 3] while stack: print(stack.pop())
Your turn! What will this code show on the screen?
your turnFix the code

Make it print every name without an error

It should print: Sunny Rocky

names = ["Sunny", "Rocky"]
i = 0
while i <= len(names):
    print(names[i])
    i += 1
This code does not work yet. Fix it, then press Run.

Practice: while or for

Solve these to lock in what you learned in this topic. Each one runs in your browser.

  1. 98.Python Program to Count the Steps of the Collatz SequenceMediumSolve
  2. 99.Python Program to Make a Number Guessing GameHardSolve