Loops
What it means
Section titled βWhat it meansβ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.
Examples
Section titled βExamplesβfor fruit in ["apple", "banana", "cherry"]: print(fruit)
for i in range(5): # 0, 1, 2, 3, 4 print(i)
count = 0while 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 cCommon mistake
Section titled βCommon mistakeβ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 conditionattempts = 0while attempts < 5: if try_connect(): break attempts += 1Quick practice
Section titled βQuick practiceβ-
Whatβs the difference between
breakandcontinue?Answer
breakexits the loop entirely;continueskips the rest of the current iteration and moves to the next one. -
What does
enumerate()give you that a plainfor item in list:doesnβt?Answer
Both the index and the value on each iteration, without manually tracking a counter. -
When does a loopβs
elseclause execute?Answer
Only if the loop finishes normally, without hitting abreak.