Skip to content
IT Vizag
← Decisions & Loops

▶ Sign up free for the video, slides & prompts

The lesson below is open to all. Enter your email once to unlock every video, slide deck, prompt and code example on this device.

Checking…

while loops

Lesson 5 of 9 · 1 min read

Repeat until something changes, and avoid infinite loops.

🎬 Video version coming soon — read it now

A for loop is great when you know how many times to repeat. A while loop repeats as long as a condition stays True, which is perfect when you don't know in advance.

🔒 Code example: sign up free (above) to unlock it.

Each time round, Python checks the condition. When count reaches 6, the condition is False and the loop ends.

Example: keep asking until the answer is valid

🔒 Code example: sign up free (above) to unlock it.

You can't know how many tries a user will need, so while is the natural choice.

Example: savings goal

🔒 Code example: sign up free (above) to unlock it.

The infinite loop

If the condition never becomes False, the loop runs forever:

🔒 Code example: sign up free (above) to unlock it.

In Colab, press the stop button next to the cell (or Runtime → Interrupt execution). Then check that something inside the loop moves it towards the end.

for or while?

  • Know the number of repeats, or looping over items? Use for.
  • Repeat until something happens? Use while.
Tip: For every while loop, ask yourself: "What line makes this condition eventually False?" If you can't point to it, you have an infinite loop.

In one line

while repeats as long as its condition is True, so make sure something inside the loop eventually makes it False.

Saved on this device. Sign in to keep progress everywhere.

Share with a friend