|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
n is even and a variable)?
We can’t create a collection of all of the even numbers from
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
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)
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
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
And that’s while loops! Let’s practice what we have learned so far:
Create a while loop to iterate over the numbers
5, and for each value, print out its value, and then print out its value added with
Create a function that returns a
listof all odd numbers between
n(inclusive). Assume that
nis always odd (solution).
Use while loops to create a rudimentary multiplication algorithm between two integers
bvia repeated addition. (solution)
If you feel that you have mastered while loops, feel free to move on to the next lesson.