← All cheat sheets

Python loops cheat sheet 🔁

for and while loops, range, break, continue, enumerate and zip. Every snippet runs in your browser, and the page prints on one sheet.

for over a list

for fruit in ["apple", "pear", "plum"]:
    print(fruit)

Runs once for each item.

range

for i in range(3):
    print(i)
print(list(range(2, 10, 3)))
print(list(range(5, 0, -1)))

range(stop), range(start, stop) and range(start, stop, step). It stops before stop.

while

balance = 100
years = 0
while balance < 150:
    balance *= 1.1
    years += 1
print(years, round(balance, 2))

Repeats while the condition is True. Make sure something changes or it never ends.

break and continue

for n in range(1, 10):
    if n % 2 == 0:
        continue
    if n > 7:
        break
    print(n)

continue skips to the next round. break leaves the loop.

enumerate and zip

names = ["Ava", "Ben"]
scores = [9, 7]
for i, name in enumerate(names, 1):
    print(i, name)
for name, s in zip(names, scores):
    print(name, s)

zip walks two lists side by side.

Loop with a running total

basket = [2.50, 1.20, 3.75]
total = 0
for price in basket:
    total += price
print(f"£{total:.2f}")

Start the total before the loop, add inside it, print after it.

for else

for n in [3, 5, 7]:
    if n % 2 == 0:
        print("found an even number")
        break
else:
    print("all odd")

The else runs only when the loop finished without break.

Start the free lessons More cheat sheets