Skip to content
skillbld
Day 6 of 14 30 minforwhilerange()break / continue

Repeat work without repeating code. Loop over sequences with for, count with range(), loop on a condition with while, and steer loops with break and continue.

By the end of today you can

  • Loop over strings and lists with for
  • Generate number sequences with range()
  • Repeat while a condition is true with while
  • Exit early with break and skip ahead with continue
  • Use the accumulator pattern and enumerate()

Imagine printing a greeting for 100 students by writing 100 print lines. Loops let you write the work once and repeat it as many times as needed.

Mind map · click a dot to fold, drag to pan

for: once per item

A for loop takes each item of a sequence in turn and runs the indented block with it:

main.py · editable
Output
Press Run to execute this code.
Diagram

range(): counting

range() produces a sequence of numbers on demand. Like slicing, the stop value is not included.

main.py · editable
Output
Press Run to execute this code.
CallProduces
range(5)0, 1, 2, 3, 4
range(2, 6)2, 3, 4, 5
range(0, 10, 3)0, 3, 6, 9
range(5, 0, -1)5, 4, 3, 2, 1

The accumulator pattern

Start with an empty total, then add to it on every pass. This is one of the most common patterns in programming:

main.py · editable
Output
Press Run to execute this code.

enumerate(): the index and the item

main.py · editable
Output
Press Run to execute this code.

while: repeat until a condition is false

Use while when you don't know how many repetitions you need, only when to stop:

main.py · editable
Output
Press Run to execute this code.

break and continue

Diagram
  • break leaves the loop immediately.
  • continue skips the rest of this pass and moves on to the next item.
main.py · editable
Output
Press Run to execute this code.

Nested loops

A loop inside a loop runs the inner loop completely for every pass of the outer one:

main.py · editable
Output
Press Run to execute this code.

Recap

  • for item in sequence: runs once per item; range() gives you numbers to loop over.
  • while condition: repeats until the condition is False. Make sure something changes!
  • break exits a loop; continue skips to the next pass.
  • Accumulate totals with total += x; use enumerate() when you need positions.

Knowledge check

Test what you learned

5 questions · pick an answer to see if you're right

0/5
  1. 1

    Which numbers does range(2, 8, 2) produce?

  2. 2

    How many times does the body of "for i in range(5):" run?

  3. 3

    What does continue do inside a loop?

  4. 4

    When should you prefer a while loop over a for loop?

  5. 5

    What is a common cause of an infinite while loop?

Finished today's lesson?