A loop repeats a block of code. Python has two kinds: a for loop that walks through items, and a while loop that repeats as long as a condition stays True.
The for loop
A for loop takes each item from a sequence one at a time:
for letter in 'abc':
print(letter)
This prints a, then b, then c.
Using range()
range() creates a series of numbers. range(n) counts from 0 up to but not including n:
for i in range(3):
print(i) # 0 1 2
You can also give a start and stop: range(2, 5) gives 2, 3, 4.
The while loop
A while loop keeps going while its condition is True. You must change something inside so it eventually stops:
count = 0
while count < 3:
print(count)
count += 1
If the condition never becomes False you get an infinite loop.
break and continue
- break stops the loop immediately.
- continue skips to the next repetition.
for i in range(5):
if i == 3:
break
print(i) # 0 1 2
Looping over a list
A for loop works naturally with lists, visiting each item in turn:
names = ['Ali', 'Sara', 'Wei']
for name in names:
print('Hello', name)
Building up a total
A common pattern is to start at zero and add inside the loop:
total = 0
for n in [10, 20, 30]:
total += n
print(total) # 60
Counting with range and a step
range can take a third number, the step, to skip values:
for i in range(0, 10, 2):
print(i) # 0 2 4 6 8
Choose a for loop when you know the items or how many times to repeat, and a while loop when you repeat until some condition changes.
Looping with a position number
Sometimes you want both the item and its position. The enumerate() helper gives you a counter alongside each item:
for i, name in enumerate(['a', 'b']):
print(i, name) # 0 a then 1 b
Without enumerate you would keep a separate counter and add one each round, which is easy to get wrong.
Remember
- range(n) stops before n, so range(3) gives 0, 1, 2.
- Always update the variable in a while loop or it never ends.
- break leaves the loop; continue jumps to the next round.