Skip to content

4. Loops

Python has two loop keywords, covering everything from Unit 1's WHILE / REPEAT UNTIL and Unit 2's repeat blocks.

while repeats as long as a condition is true — the same shape as the dishwashing example back in Unit 1:

count = 0
while count < 5:
    count = count + 1
    print(count)
1
2
3
4
5

for repeats over a known sequence of values, most often a range(...):

for i in range(5):
    print(i)
0
1
2
3
4

Note that range(5) counts 0, 1, 2, 3, 4 — five numbers starting at zero, not five-through-one.

Try it

Write a while loop that counts from 1 to 5, printing each number — the same loop from Unit 1, Lesson 6, now in real Python.

Tip

Same warning as Unit 1: a while loop whose condition never becomes false is an infinite loop. If your terminal looks frozen, Ctrl+C stops it.

Next: Lists and Dictionaries →