Python while Loops · Exercises
Beginner

Python while Loops Exercises

4 exercises that build on the Python while Loops lesson, from easy to hard. Each one is checked in your browser when you press Check. Stuck? Use the hint before peeking at the solution.

What this lesson covers: A while loop keeps repeating a block of code for as long as its condition is True, checking the condition again before every round. By the end you can write a while loop that ends on its own, leave a loop early with break, keep reading input until a sentinel value, and recognise (and stop) an infinite loop. You will practise: Count down to Go!; Predict the tripling loop; Stop the endless race; Read prices until done.

0 / 4 completed

Python while Loops practice exercises

1. Count down to Go!

Write code Easy

Use a while loop to print the numbers from start down to 1, one per line, and then print Go!. With start = 5 the output is:

5
4
3
2
1
Go!
Your code
start = 5

# your while loop here

2. Predict the tripling loop

Predict the output Medium

Read the code and type exactly what it will print. Then press Check to run it and compare.

Read this code
n = 1
while n < 30:
    n = n * 3
    print(n)
print("end:", n)

3. Stop the endless race

Fix the bug Medium

Each lap uses 15 units of fuel, so with 60 units the car should do 4 laps and then print Out of fuel after 4 laps. Instead the loop never ends (the run is stopped by the output limit — or press Stop). Find and fix the bug.

Your code
fuel = 60
laps = 0
while fuel > 0:
    laps += 1
    fuel - 15
    print("Lap", laps, "fuel left:", fuel)
print("Out of fuel after", laps, "laps")

4. Read prices until done

Write code Hard

Read prices with input() until the user types done. Keep a running total (a float) and a count of prices entered. After the loop print Items: 3 and Total: 19.75 (using your variables).

The Input box already contains the lines 4.5, 3, 12.25 and done.

Your code
total = 0
count = 0

# read prices until the user types done

Next lessonPython range() Function

More Python while Loops examples · All Python exercises