Previous Lesson Table of Contents Next Lesson

Suppose you want to iterate using a loop, but you don’t know the exact collection over which to do the iterating? For example, what if we want to iterate over all even numbers between 0 and n (where n is even and a variable)?

We can’t create a collection of all of the even numbers from 0 to n because it isn’t well-defined. Also if n were a 1000, writing out this collection would be very tedious to say the least. However, we have recourse, which is a while loop:

# Assume n is even.
while n >= 0:
    print(n)
    n -= 2

A while loop can be thought of as an if statement that keeps being checked over and over again until it finally becomes false. Each time the conditional is true, we execute the code associated with that conditional.

Note that it’s very important that the conditional will become false at some point. In this case, we are subtracting 2 from n each time (-= is known as the decrement operator). Thus, there will come a time when n >= 0 is false because n is negative. At that point, we will exit the while loop.

Suppose we forgot the decrement line and just wrote this:

while n >= 0:
    print(n)

Unless n < 0 to begin with, we would print n forever because n >= 0 is always true!

Finally, we should point out that although for loops and while loops are somewhat different, we can in fact write for loops as while loops in some cases:

for x in ["a", "b", "c"]:
    print(x)

Here is an equivalent representation as a while loop:

l = ["a", "b", "c"]
index = 0

while index < len(l):
    print(l[index])
    index += 1

In both cases, we are just printing out the letters "a", "b", and "c". The while loop example works by incrementing the index until it exceeds the last possible index for a list, which is len(l) - 1. The index of the first element is 0 (zero-indexing).

And that’s while loops! Let’s practice what we have learned so far:

  • Create a while loop to iterate over the numbers 1 through 5, and for each value, print out its value, and then print out its value added with 1. (solution)

  • Create a function that returns a list of all odd numbers between 0 and n (inclusive). Assume that n is always odd (solution).

  • Use while loops to create a rudimentary multiplication algorithm between two integers a and b via repeated addition. (solution)

If you feel that you have mastered while loops, feel free to move on to the next lesson.