Python has two loop keywords — for and while. Python's for always loops over an iterable (a list, string, range, and so on) — there's no separate keyword needed for counting a fixed number of times versus looping over a collection.
You already used this looping over lists and dictionaries. Looping a fixed number of times uses range():
for i in range(5):
print(f"Count: {i}") # 0, 1, 2, 3, 4 — range(5) stops before 5
for i in range(1, 6):
print(f"Count: {i}") # 1, 2, 3, 4, 5There is no C-style for (i = 0; i < 5; i++) in Python — range() is how you get a counted loop.
Repeats as long as a condition stays true:
count = 0
while count < 3:
print(f"Iteration {count}")
count += 1 # Python has no ++ operator — this is the idiomatic wayNo ++ in Python
Python has no ++ or -- increment/decrement operators at all — count += 1 is the only way to increase a variable by one. This is a deliberate language design choice, not an oversight.
Python has no do-while loop — a loop that always runs its body at least once before checking the condition. The common workaround is a while True loop with a break at the point where the condition would normally be checked:
count = 10
while True:
print(f"This runs once, even though {count} is not < 3.")
if not (count < 3):
breakfor i in range(1, 11):
if i == 6:
break # stops the loop entirely
if i % 2 == 0:
continue # skips this iteration, keeps looping
print(i, end=" ")
# Output: 1 3 5This one is genuinely distinctive: a loop can have its own else, which runs if the loop finished normally — that is, only if break was never hit:
numbers = [2, 4, 6, 8]
for n in numbers:
if n % 2 != 0:
print("Found an odd number.")
break
else:
print("All numbers are even.") # runs, since break never firedIt reads oddly at first, but it's a clean way to express "search for something, and do X only if it wasn't found" without a separate flag variable to track whether break happened.