Part 3: Python Programming
Part 3: Python Programming — read through each chapter in order. Diagrams, tables and worked examples included.
7. Loops
Loops
Computers excel at repetition. A loop runs a block of code many times without you writing it out again and again. Python has two loops: the for loop, which repeats once for each item in a sequence, and the while loop, which repeats as long as a condition stays true.
The for loop and range()
A for loop walks through the items of a sequence, giving you one item per pass. The range() function generates a sequence of numbers, which is the usual way to repeat a fixed number of times. range(5) produces 0, 1, 2, 3, 4 (it stops before 5):
range can take a start, stop, and step: range(2, 11, 2) gives 2, 4, 6, 8, 10.
Iterating over sequences
You can loop directly over the characters of a string or, as you will see later, the items of a list:
The while loop
A while loop keeps going as long as its condition is true. You must make sure something inside the loop eventually makes the condition false, or the loop will run forever:
break and continue
Two keywords give you finer control. break leaves the loop immediately. continue skips the rest of the current pass and jumps to the next one:
Odd numbers 1 and 3 print. Even numbers 2 and 4 are skipped by continue, and when n reaches 5 the break stops the loop entirely.
The loop else clause
Both loops may have an else block that runs only if the loop finished normally without hitting a break. It is handy for search loops:
Choosing between for and while
| Use a for loop when... | Use a while loop when... |
|---|---|
| You know how many times to repeat | You repeat until a condition changes |
| You are walking through a sequence | The number of repeats is unknown in advance |
| Example: process each student | Example: keep asking until input is valid |
Loops turn a few lines of code into enormous amounts of work. Practice by printing a multiplication table for a number using a for loop and range.