Python While Loops
What you will learn
- How a
whileloop repeats a block while a condition is true - The three parts of a loop: start, test, update
- Common patterns: counting down, totalling, reading input until valid
- Loops that run zero times
- What an infinite loop is, and how
while Truewithbreakuses it on purpose
1. Repeating code
A loop repeats a block of code. A while loop repeats as long as its condition is true:
count = 1
while count <= 3:
print("count is", count)
count += 1
print("done, count =", count)
count is 1
count is 2
count is 3
done, count = 4
The layout is like an if (lesson 5.2): the word while, a condition, a colon, and an indented block. The difference is that after the block runs, Python goes back to the condition and checks it again. When the condition becomes false, the loop ends and the program continues after the block.
Quick check: how many times does `print("count is", count)` run above?
3 times, for count equal to 1, 2 and 3. When count reaches 4, the test count <= 3 is false.
2. The three parts of a loop
Almost every while loop has three parts:
| Part | In the example | Job |
|---|---|---|
| start | count = 1 |
set the starting value before the loop |
| test | count <= 3 |
decide whether to go round again |
| update | count += 1 |
change something so that the test can become false |
If you forget the update, the test never changes, and the loop never ends. That is called an infinite loop (section 6).
3. Counting patterns
You can count in any step, including downwards:
n = 10
while n > 0:
print(n, end=" ")
n -= 3
print()
10 7 4 1
The end=" " keeps the output on one line (lesson 1.2).
Totalling
Add to a running total each time round (the next lessons show shorter ways):
total = 0
i = 1
while i <= 100:
total += i
i += 1
print(total)
5050
The loop adds 1 + 2 + ... + 100.
Walking through a string
A while loop can step through the positions of a text:
text = "hello"
pos = 0
while pos < len(text):
print(text[pos], end="-")
pos += 1
print()
h-e-l-l-o-
A for loop (lesson 6.2) is the better tool for this, but the example shows how an index moves.
4. A loop may run zero times
The test is checked before the first pass. If it starts false, the block is never run:
x = 5
while x < 3:
print("never")
print("skipped the loop")
skipped the loop
5. Loops that depend on something unknown
A while loop shines when you do not know in advance how many times to repeat. Examples are "until the user types a valid answer", "until the balance reaches a goal":
balance = 1000
years = 0
while balance < 2000:
balance *= 1.07
years += 1
print(years, round(balance, 2))
11 2104.85
A balance of 1000 growing by 7% a year (a made-up rate) passes 2000 after 11 years.
Asking again until the answer is valid
Reading input until it is acceptable is a classic. In the terminal it looks like this (the user types the text after each prompt):
answer = input("How many? ")
while not answer.isdigit():
print("Please type a whole number.")
answer = input("How many? ")
print("You asked for", int(answer))
How many? abc
Please type a whole number.
How many? -3
Please type a whole number.
How many? 7
You asked for 7
Notice the pattern: ask once before the loop, test, and ask again inside the loop. (Lesson 4.3 explained isdigit: it is false for "-3" and for decimals.)
The Euclid method
A beautiful use is the greatest common divisor of two numbers: keep replacing the pair (a, b) by (b, a % b) until b is zero:
a = 48
b = 18
while b != 0:
a, b = b, a % b
print("gcd", a)
gcd 6
(The same job is done by math.gcd, lesson 3.6. Here you see how it works inside.)
6. The infinite loop
If the test never becomes false, the loop never ends and the program seems frozen:
n = 1
while n > 0: # n never decreases, so this never stops
n += 1
To stop a program stuck in a loop, press Ctrl + C in the terminal. Python raises KeyboardInterrupt and stops.
Sometimes you want a loop that runs until something inside decides to stop it. The standard form is while True with break (lesson 6.3):
while True:
print("once")
break
once
Lesson 6.7 covers how to design such loops well.
Worked example: how many digits?
Count the digits of a whole number by dividing it by 10 until nothing is left.
num = 12345
digits = 0
while num > 0:
num //= 10
digits += 1
print(digits)
5
| Pass | num before |
After num //= 10 |
digits |
|---|---|---|---|
| 1 | 12345 | 1234 | 1 |
| 2 | 1234 | 123 | 2 |
| 3 | 123 | 12 | 3 |
| 4 | 12 | 1 | 4 |
| 5 | 1 | 0 | 5 |
When num reaches 0, the test num > 0 is false and the loop stops. The number is made up. (len(str(12345)) gives the same answer more simply.)
Common mistakes
- Forgetting the update, which makes an infinite loop.
- Updating in the wrong direction (
n += 1when counting down). - Off-by-one errors:
<instead of<=, so the last value is missing. - Forgetting to set the start value before the loop (a
NameError). - Forgetting the colon or the indentation (lesson 5.2).
Key takeaways
while condition:repeats its block as long as the condition is true; the test comes before each pass.- A loop needs a start, a test and an update.
- It may run zero times, or forever if the update is missing; Ctrl + C stops it.
- It suits "repeat until..." problems: valid input, a goal reached, a value shrinking to zero.
while Truewithbreakis the way to say "repeat until I say stop".
Practice
1. Write a loop that prints the numbers 1 to 5.
Show answer
n = 1
while n <= 5:
print(n)
n += 1
2. What does this print: n = 3 then while n > 0: print(n) n -= 1?
Show answer
3, 2 and 1, each on its own line.
3. Why does x = 10 followed by while x > 0: print(x) never stop?
Show answer
x is never changed inside the loop, so x > 0 stays true. Add x -= 1 to update it.
4. How many times does i = 0 then while i < 5: with i += 2 run its block?
Show answer
3 times, for i equal to 0, 2 and 4. After that i is 6.
5. Write a loop that adds the even numbers from 2 to 20 into total.
Show answer
total = 0
n = 2
while n <= 20:
total += n
n += 2
The result is 110.
6. Write the three-line pattern that asks for a password again until the user types secret.
Show answer
pw = input("Password: ")
while pw != "secret":
pw = input("Try again: ")