range() & while
beginner12 min readLesson 21 of 169
Counting with range, enumerate, zip โ and while with its infinite-loop trap.
range() produces a sequence of numbers โ how you count in Python:
range(5) # 0, 1, 2, 3, 4 (stop excluded!)
range(1, 6) # 1, 2, 3, 4, 5 (start, stop)
range(0, 10, 2) # 0, 2, 4, 6, 8 (start, stop, step)
range(10, 0, -1) # 10, 9, ..., 1 (counting down)
range(stop) never includes stop โ the half-open rule again, same as
slicing. Combine with list() to see it: list(range(4)) โ [0, 1, 2, 3].
enumerate: value AND position
for i, fruit in enumerate(fruits):
print(i, fruit) # 0 apple, 1 pear, 2 plum
zip: walk two lists together
names = ["a", "b"]
scores = [9, 7]
for name, score in zip(names, scores):
print(name, score)
while: loop while a condition holds
count = 3
while count > 0:
print(count)
count -= 1
print("liftoff")
while re-checks the condition each round. If nothing inside makes the
condition false, the loop never ends โ the infinite loop, the classic
beginner trap. When a loop must end, something in the body must move toward
the exit (decrement a counter, change a flag...).