CodeBlanks Logo Icon CodeBlanks

The while loop

Learn conditional loops with while.

The while loop

A while loop repeats a block as long as a condition is true:

count = 0
while count < 3:
    print(count)
    count += 1

This prints 0, 1, 2. The condition is checked at the start of each iteration; when it becomes False the loop ends.

In a while loop the condition must become False somewhere, or you get an infinite loop. count += 1 increments count each time.

while vs for

for runs for the length of a collection, while runs as long as a condition is true. Which to pick?

  • for: when the collection or range is known.
  • while: when the number of iterations is unknown, depending on a condition.

Example: waiting for the user to type 'quit' uses while.

Practice Count with while

Assign count = 0. Write while count < 3: print(count) and count += 1.

Starter code

main.py
# while loop

Sample solution

main.py
count = 0
while count < 3:
    print(count)
    count += 1

Expected output

0
1
2

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What prevents an infinite while loop?

  • A print call
  • Missing break
  • The condition becoming False Correct answer
  • A for loop

Explanation: The condition must become False, or the loop is infinite.

2 Complete the while condition

Question
count = 0
while count ____ 3:
    print(count)
    count += 1
Answer
count = 0
while count < 3:
    print(count)
    count += 1

Explanation: count < 3 produces 0, 1, 2.

3 Match the loop types

Term Meaning
for Collection loop
while Condition loop
range Number range
count += 1 Increment

All lessons in Beginner