🚀 New batches open: Advanced Excel • Power BI • SQL • AI for Analytics — Book a free demo

Day 8 — Python while loops, break and continue

A for loop runs a known number of times. A while loop runs until something becomes true — which is powerful, and easy to get wrong.

while

The one real danger Forget count += 1 and the condition never becomes false — the loop runs forever. This playground stops after a while and tells you; a real program would just hang.
Every while needs something inside it that moves towards the exit.

A countdown

break — leave the loop early

continue — skip this one, carry on

for or while?

  • for — you know what you are looping over: a list, a range, rows of data. This is what you will use 95% of the time.
  • while — you are waiting for a condition: a balance reaching zero, a retry succeeding, input being valid.

A worked example

How many months until savings reach a target?

Try these yourself

  1. Count down from 10 to 1 with a while loop.
  2. Use break to stop at the first negative number in a list.
  3. Use continue to skip empty strings while printing a list of names.
  4. Work out how many months at 8000 it takes to reach 50000.

Ready for pandas and real projects?

This tutorial covers core Python. Our Data Analytics course takes you into pandas, NumPy, real files and visualisation, with mentor support and portfolio projects.

See the course →