Lesson 7 of 10

The while loop

Goal

Repeat while a condition holds

01

Explanation

A for loop knows in advance which items it will go through. When you don't know how many times you'll repeat, like "until the savings reach the goal" or "until the connection succeeds", use while: it repeats as long as its condition is true, checking it before every iteration.

You'll often pair it with a variable that starts at zero and grows with every iteration, like saved += deposit, plus a counter alongside it that counts the iterations, like months += 1.

The loop only ends if something inside it eventually makes its condition false. If you forgot saved += deposit, saved < goal would stay true forever and the program would never stop. So before you write any while, ask yourself: which line is going to end it?

02

Your task

Someone saves 300 in the first month, and every month after that they save 100 more than the month before. Use a while loop to increase saved and months until saved reaches goal, then print the result.

Checks

4 checks
  1. saved reached the goal
  2. months is nine, because the loop stopped in the first month that reached the goal
  3. saved is 6300 when the loop stops
  4. The calculation uses a while loop
03

Hints

0/3
Track lessons0 of 10 done

Start with the most beginner-friendly language there is, and use it to learn variables, strings, lists, conditions, loops and functions.

Beginner level, 10 lessons, 2 hours in total.

main.py
OutputPython (Pyodide)

Loading Python. This only happens once. Your browser keeps it after that.

–/4

Checks start once the environment is ready.

4 checks listed under “Your task”.

Track lessons0 of 10 done

Start with the most beginner-friendly language there is, and use it to learn variables, strings, lists, conditions, loops and functions.

Beginner level, 10 lessons, 2 hours in total.