Python has two loop keywords — for and while — compared to PHP's four. for covers what PHP splits across for and foreach, since Python's for always loops over an iterable.
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 — same idea as PHP's while:
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 doesn't have PHP's do-while. 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 5