How it works
Indentation defines blocks, so structure is enforced by layout. A for loop iterates over a sequence directly rather than over indices.
Iterate over items when the index is not needed, and enumerate when it is.
Common error
Looping over a range of indices out of habit, which is longer and easier to get wrong than iterating directly.
Worked example
Python
total = 0
for value in range(1, 6):
if value % 2 == 0:
total += value
print(total)Output
6range stops before its upper endpoint. The conditional selects 2 and 4, whose sum is 6.
Exercises
1.4.1 · Trace
Determine the exact output and explain the state changes.
Python
n = 1
while n < 10:
n *= 2
print(n)Show solution
Output
16The successive values are 2, 4, 8, 16. The next condition check ends the loop.
1.4.2 · Write code
Create and print the list of odd integers from 1 through 7.
Show solution
Use a stepped range whose stop excludes 8.
One valid solution
odds = list(range(1, 8, 2))
print(odds)Expected output
[1, 3, 5, 7]