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
forloop — repeats a set number of times, usingrange(n)for the numbers0throughn-1whileloop — repeats as long as a condition staysTrue, for when you don't know the count ahead of timebreak— exits a loop immediately, even if its condition is still true
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:
- A worked example, fully written out
- Two guided practices — change a few values, then fill in some blanks
- Two independent practices — write your own from scratch, different scenario each time
- An optional stretch, if you want to go further
- 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.
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.