Python while loop exercises for beginners

Fourteen while loop exercises, from easy to harder, each with a hint and a worked answer. Write your code in the box, press Check, and you'll know straight away if it's right. Nothing to install.

How a while loop works

A while loop repeats its indented lines for as long as its condition is True. Almost every while loop has three parts: a starting value, a condition, and a line that changes the value so the loop can end.

main.py
Output
1
2
3
4
5
Done!

Python checks the condition before every pass. When count reaches 6, count <= 5 is False, so the loop stops and the program carries on with the first line that isn't indented.

while or for? Use for when you know how many times to repeat ("do this 10 times"). Use while when you repeat until something happens: until the password is right, until the user types 0, until the plant is tall enough.

The exercises

Each exercise says exactly what to print. Press Run to try your code, and Check to compare its output with the right answer. Exercises that use input() are checked with the answers listed in the task. Your ticks are saved in this browser.

1

Count from 1 to 10

Easy✓

Print the numbers 1 to 10, each on its own line, using a while loop.

main.py
Output
Write your code, then press Run to try it or Check to test it.
Hint

Keep going while count is 10 or less, and add 1 to count inside the loop.

Show the answer
count = 1
while count <= 10:
    print(count)
    count = count + 1

Output

1
2
3
4
5
6
7
8
9
10
2

Countdown to lift-off

Easy✓

Count down from 10 to 1, then print Lift off!

main.py
Output
Write your code, then press Run to try it or Check to test it.
Hint

Take 1 away each time round. Lift off! goes after the loop, with no indent, so it prints once.

Show the answer
count = 10
while count >= 1:
    print(count)
    count = count - 1
print("Lift off!")

Output

10
9
8
7
6
5
4
3
2
1
Lift off!
3

Even numbers

Easy✓

Print the even numbers from 2 to 20, one per line.

main.py
Output
Write your code, then press Run to try it or Check to test it.
Hint

Start at 2 and add 2 each time, instead of 1.

Show the answer
number = 2
while number <= 20:
    print(number)
    number = number + 2

Output

2
4
6
8
10
12
14
16
18
20
4

Add up 1 to 100

Easy✓

Add up all the whole numbers from 1 to 100, and print only the total.

main.py
Output
Write your code, then press Run to try it or Check to test it.
Hint

Inside the loop, add number to total, then move number on by 1. Print after the loop ends.

Show the answer
total = 0
number = 1
while number <= 100:
    total = total + number
    number = number + 1
print(total)

Output

5050
5

The 7 times table

Easy✓

Print the 7 times table from 7 x 1 = 7 to 7 x 10 = 70.

main.py
Output
Write your code, then press Run to try it or Check to test it.
Hint

An f-string makes each line: f"7 x {n} = {7 * n}".

Show the answer
n = 1
while n <= 10:
    print(f"7 x {n} = {7 * n}")
    n = n + 1

Output

7 x 1 = 7
7 x 2 = 14
7 x 3 = 21
7 x 4 = 28
7 x 5 = 35
7 x 6 = 42
7 x 7 = 49
7 x 8 = 56
7 x 9 = 63
7 x 10 = 70
6

The growing plant

Medium✓

A plant is 2 cm tall and doubles in height every week. Print its height each week, like Week 1: 4 cm, until it's taller than 100 cm. Then print It took 6 weeks. (using your weeks variable).

main.py
Output
Write your code, then press Run to try it or Check to test it.
Hint

Loop while height is 100 or less. Double it, add 1 to weeks, then print.

Show the answer
height = 2
weeks = 0
while height <= 100:
    height = height * 2
    weeks = weeks + 1
    print(f"Week {weeks}: {height} cm")
print(f"It took {weeks} weeks.")

Output

Week 1: 4 cm
Week 2: 8 cm
Week 3: 16 cm
Week 4: 32 cm
Week 5: 64 cm
Week 6: 128 cm
It took 6 weeks.
7

Count the digits

Medium✓

Count how many digits are in number without turning it into text, and print 90210 has 5 digits.

main.py
Output
Write your code, then press Run to try it or Check to test it.
Hint

// 10 knocks the last digit off a number. Count how many times you can do it before it reaches 0. Keep a copy of the original number to print.

Show the answer
number = 90210
digits = 0
left = number
while left > 0:
    left = left // 10
    digits = digits + 1
print(f"{number} has {digits} digits")

Output

90210 has 5 digits
8

The password door

Medium✓

Keep asking Password: until the user types banana42. Print Wrong, try again. after each wrong guess, and Door open! at the end. The check types apple, Banana42, then banana42.

main.py
Output
Write your code, then press Run to try it or Check to test it.
Hint

Ask once before the loop, and again at the bottom of the loop. Loop while the password is not right: !=.

Show the answer
password = input("Password: ")
while password != "banana42":
    print("Wrong, try again.")
    password = input("Password: ")
print("Door open!")

Output (with the answers apple, Banana42, banana42)

Password: apple
Wrong, try again.
Password: Banana42
Wrong, try again.
Password: banana42
Door open!
9

Add numbers until 0

Medium✓

Keep asking for numbers and adding them up. When the user types 0, stop and print Total: 18 (the total). The check types 5, 10, 3, then 0.

main.py
Output
Write your code, then press Run to try it or Check to test it.
Hint

input() always gives text. Wrap it in int() so you can add the numbers.

Show the answer
total = 0
number = int(input("Number (0 to stop): "))
while number != 0:
    total = total + number
    number = int(input("Number (0 to stop): "))
print(f"Total: {total}")

Output (with the answers 5, 10, 3, 0)

Number (0 to stop): 5
Number (0 to stop): 10
Number (0 to stop): 3
Number (0 to stop): 0
Total: 18
10

Guess the number

Medium✓

The secret number is 7. Keep asking for a guess. Print Too low! or Too high! after each wrong guess. When it's right, print Correct! You took 3 guesses. with the real count. The check guesses 3, 9, then 7.

main.py
Output
Write your code, then press Run to try it or Check to test it.
Hint

Give guess a starting value that can't be right, like 0, so the loop runs at least once. Ask inside the loop.

Show the answer
secret = 7
guesses = 0
guess = 0
while guess != secret:
    guess = int(input("Your guess: "))
    guesses = guesses + 1
    if guess < secret:
        print("Too low!")
    elif guess > secret:
        print("Too high!")
print(f"Correct! You took {guesses} guesses.")

Output (with the answers 3, 9, 7)

Your guess: 3
Too low!
Your guess: 9
Too high!
Your guess: 7
Correct! You took 3 guesses.
11

Fix the endless loop

Fix it✓

This loop should print 1 to 5 and then Finished, but it never stops. Press Run to see what happens, then fix it.

main.py
Output
Write your code, then press Run to try it or Check to test it.
Hint

Nothing inside the loop changes count, so count <= 5 stays True for ever.

Show the answer
count = 1
while count <= 5:
    print(count)
    count = count + 1
print("Finished")

Output

1
2
3
4
5
Finished
12

Stop with break

Harder✓

Use while True: to keep asking for a word and printing it in capitals. When the word is stop, leave the loop with break and print Bye!. The check types hello, python, then stop.

main.py
Output
Write your code, then press Run to try it or Check to test it.
Hint

Check for stop before printing, so STOP is never shown.

Show the answer
while True:
    word = input("Word: ")
    if word == "stop":
        break
    print(word.upper())
print("Bye!")

Output (with the answers hello, python, stop)

Word: hello
HELLO
Word: python
PYTHON
Word: stop
Bye!
13

Reverse a number

Harder✓

Turn 1234 into 4321 using maths only, and print it. Use % 10 to get the last digit and // 10 to remove it.

main.py
Output
Write your code, then press Run to try it or Check to test it.
Hint

Each time round, move reverse one place to the left (times 10), then add the digit you just took off.

Show the answer
number = 1234
reverse = 0
while number > 0:
    digit = number % 10
    reverse = reverse * 10 + digit
    number = number // 10
print(reverse)

Output

4321
14

Hailstone numbers

Harder✓

Start with n = 6. While n isn't 1: if it's even, halve it with //, otherwise make it 3 * n + 1. Print n after every step, then print Steps: 8 with the number of steps.

main.py
Output
Write your code, then press Run to try it or Check to test it.
Hint

n % 2 == 0 is True for even numbers. Use // 2 so n stays a whole number.

Show the answer
n = 6
steps = 0
while n != 1:
    if n % 2 == 0:
        n = n // 2
    else:
        n = 3 * n + 1
    steps = steps + 1
    print(n)
print(f"Steps: {steps}")

Output

3
10
5
16
8
4
2
1
Steps: 8

Common while loop mistakes

Play the game version

Each of these games teaches one idea from this page, with a short narrated video and six levels to clear.

Questions people ask

What is a while loop in Python?

A while loop repeats a block of code for as long as its condition is True. Python checks the condition before each pass, and stops as soon as it's False.

When should I use a while loop instead of a for loop?

Use while when you don't know in advance how many times to repeat, such as asking until the answer is right. Use for to repeat a set number of times or to go through a list.

How do I stop an infinite while loop?

Make sure something inside the loop changes the condition, or use break. If one is already running, press Ctrl+C in a terminal, or Stop in the browser.

What does while True mean in Python?

while True: repeats for ever, so it needs a break inside, usually in an if, to leave the loop when something happens.

Can a while loop use input()?

Yes. Ask once before the loop, check the answer in the condition, and ask again inside the loop. Wrap input() in int() if you need a number.

Learn Python with games

Every idea on this page has its own game in the course, with a short video and six levels. The three games in Module 1 are free: no account, nothing to install.

Every idea on this page has its own game in the course. Pick up where you left off.

Play the first game freeContinue the course