Loops in Python

From the Python cheat sheet ยท Control Flow ยท verified Jul 2026

Loops

for and while loops with break, continue, and else clauses.

python
# for loop
for item in items:
    print(item)

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

# while loop
while count > 0:
    count -= 1

# break / continue
for x in range(10):
    if x == 3: continue  # skip 3
    if x == 7: break     # stop at 7
๐Ÿ’ก Use enumerate() instead of range(len()) โ€” it's cleaner and more Pythonic
โšก zip() pairs elements from multiple iterables โ€” stops at the shortest
๐Ÿ“Œ The else clause on a loop runs only if the loop did NOT hit a break
๐ŸŸข Use continue to skip an iteration, break to exit the loop entirely
loopsforwhilebreakcontinue

More Python tasks

Back to the full Python cheat sheet