Chapter 11 of 15All chapters
Chapter 11 of 15
Loops
for, while, range and how to stop early.
for and range
A for loop walks anything you can iterate: a list, a string, a dict, a file. range(start, stop, step) counts up to but never including stop, so range(2, 8, 2) yields 2, 4 and 6.
- enumerate(items) gives index and value together.
- zip(a, b) walks two sequences side by side.
while and control
A while loop repeats until its condition fails, which suits waiting on something rather than walking a sequence. break leaves the loop immediately and continue skips to the next round.