Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 2.3 — Repeating with while
Python · Example 1 of 2

Counters, totals and a growing balance

Change the start of the countdown to 5, and change the target balance to 200. Predict the number of years first.

A while loop repeats a block of code for as long as its condition stays True. You must make something inside the loop change the condition, or the loop never ends.

Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.

Ready for more? This phase has 6 hands-on exercises with automatic checks.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

Use a while loop to print the numbers 1 to 5, one per line.

02

Start with value = 1 and steps = 0. Double value while it is at most 1000, counting the steps. Print value and steps.

03

A list data = [5, 10, 0, 7] ends data at the first 0. Use a sentinel while loop to add up the numbers before the 0 and print Total: 15.

Explain it without notes

01

How does a while loop work, step by step?

02

What is an infinite loop and how do you spot one while reading code?

03

What is a sentinel loop? Give an example.

04

When would you choose while over for?

Counters, totals and a growing balance
Sign in to run this example in your browser.

Expected output

Countdown: 3
Countdown: 2
Countdown: 1
Liftoff
Sum of 1..5: 15
Years: 5 Balance: 161.05