Loops

Every program so far has run each line exactly once, top to bottom. Loops let you repeat a block of code — either a fixed number of times, or until something changes. This is where your programs stop feeling like a list of instructions and start feeling like actual software.

What You'll Learn

  • for loop — repeats a set number of times, using range(n) for the numbers 0 through n-1
  • while loop — repeats as long as a condition stays True, for when you don't know the count ahead of time
  • break — exits a loop immediately, even if its condition is still true
Watch out for: a while loop needs something inside it that eventually makes its condition False — forget to update that variable and you've built an infinite loop. If a cell seems frozen, that's almost always why.

Today's Activity

Today's practice happens inside the notebook below — work through it top to bottom:

  1. A worked example, fully written out
  2. Two guided practices — change a few values, then fill in some blanks
  3. Two independent practices — write your own from scratch, different scenario each time
  4. An optional stretch, if you want to go further
  5. One check-your-understanding question to close

Download the notebook, save it into your 1_foundations folder in your cloned repo, and open it in VS Code. Commit once you've saved it, then commit again when you're done for the day.

Download 1.5_Loops.ipynb

New to notebooks? See Using Jupyter Notebooks first.

What's Next

Coming up: 1.6 — Functions, where you start packaging up reusable pieces of your code.