The while loop

Loops, lesson 1 of 5

🔁 Loops, lesson 1 of 5

The while loop

Repeat code for as long as a condition stays True.

8 min

1 exercise

2 quizzes

0/3 solved

Getting Python ready… examples can run in a moment.

Computers are great at doing the same thing over and over. A while loop repeats its indented body for as long as its condition is True:

while condition:
    do_something()

Python checks the condition before every pass. When it becomes False, the loop ends and the program carries on after it.

Example

Rocket countdown

Start the countdown at 10 instead. What happens if you start it at 0?

Quiz

What does this print?

Use while when you don't know in advance how many repetitions you need: keep saving until you hit a goal, keep asking until the answer is right.

Example

Savings goal

Try saving 80 a week, or raise the goal to 1000.

Example

Guess the number

One line per input() call

The guesses 3, 9 and 7 are typed in for you. The loop keeps asking until a guess matches secret.

Exercise

Fold paper to Everest

A sheet of paper is 0.1 mm thick, and every fold doubles its thickness. How many folds until it is taller than Mount Everest (8,849,000 mm)?

Use a while loop: while thickness is not more than everest, double thickness and add 1 to folds.

Quiz

When does Python check a while loop's condition?