Skip to content

Loops

Python has two loop constructs: for (iterates over items in a sequence β€” a list, string, range, etc.) and while (repeats as long as a condition stays true). break exits a loop early; continue skips to the next iteration; loops also support an else clause that runs only if the loop completes without hitting a break.

for fruit in ["apple", "banana", "cherry"]:
print(fruit)
for i in range(5): # 0, 1, 2, 3, 4
print(i)
count = 0
while count < 3:
print(count)
count += 1
for n in range(10):
if n == 5:
break # stop the loop entirely
if n % 2 == 0:
continue # skip to the next iteration
print(n) # prints 1, 3
for i, value in enumerate(["a", "b", "c"]):
print(i, value) # 0 a / 1 b / 2 c

Writing while True: without a reliable way to exit β€” an easy way to accidentally write an infinite loop, especially if the condition that should trigger break never becomes true due to a logic bug.

# Risk of infinite loop if user never enters "quit"
while True:
command = input("Enter command: ")
if command == "quit":
break
process(command)
# Safer pattern with an explicit, bounded condition
attempts = 0
while attempts < 5:
if try_connect():
break
attempts += 1
  1. What’s the difference between break and continue?

    Answerbreak exits the loop entirely; continue skips the rest of the current iteration and moves to the next one.
  2. What does enumerate() give you that a plain for item in list: doesn’t?

    AnswerBoth the index and the value on each iteration, without manually tracking a counter.
  3. When does a loop’s else clause execute?

    AnswerOnly if the loop finishes normally, without hitting a break.