For and While Loops
Level 3 · Decisions and loops
How a loop runs the same lines again and again. For loops over a list, while loops on a test, break to stop, and the loop that never ends.
Course contentsLesson 11 of 18
Level 1 · What a program is
Level 2 · Values and variables
Level 3 · Decisions and loops
Level 4 · Functions
Level 5 · Errors and debugging
Level 6 · Good code habits
After this lesson you can
- Write a for loop over a list
- Write a while loop that stops
- Spot and fix an infinite loop
13 mincovers 5 glossary entries
Worth reading first: If, Else and Match, Lists, Dictionaries and Sets
How a program repeats the same lines
A loop runs the same lines again and again. It saves you writing a line 100 times when the job is to do one thing to 100 items. Python has two kinds. A for loop runs once for each item in a collection. A while loop keeps going as long as a test is True.
A for loop reads for name in names:, then a block. Python takes the first item, puts it in name and runs the block. Then it takes the next item, until the list runs out. It stops by itself. To count, use range: for i in range(5): runs with i set to 0, 1, 2, 3 and 4.
range(5) stops before 5. That matches list indexes, which also start at 0. So for i in range(len(names)): visits every spot in the list exactly once. But you rarely need the number. for name in names: is shorter and cannot go past the end.
A while loop checks its test before each pass. while lives > 0: runs until lives drops to 0. Use it when you cannot know the number of passes in advance, such as asking for a password until it is right. Something inside the block must change, or the test stays True for ever.
That is an infinite loop: one that never ends. The program seems to freeze, or it prints the same line without stopping. The usual cause is forgetting to change the value the test checks. In a terminal, Ctrl+C stops a Python program that is stuck.
break stops a loop at once, even mid-list. It is handy when you find what you were looking for. continue is its partner: it skips the rest of this pass and goes straight to the next one. Both work in for and while loops alike.
A common mistake is changing a list while a for loop walks over it. Removing items mid-loop makes Python skip some. Loop over a copy instead, or build a new list with the items you want to keep.
for name in ["Ana", "Ben", "Cy"]:
print("Hi", name)
lives = 3
while lives > 0:
print("Lives left:", lives)
lives = lives - 1 # without this line, it never ends
for n in range(1, 100):
if n % 7 == 0:
print("First multiple of 7:", n)
breakWorked example
The words for this lesson5
Check yourself
Which numbers does for i in range(4): give i?
Finished this lesson?
Marking it complete also marks its 5 glossary entries learned, which updates your roadmap and your saved page. 0 are already marked.