How to repeat with loops

Loop over an iterable

A for loop visits each item from a list, string, range, file, or other iterable.

for name in ["Ada", "Grace", "Guido"]:
    print(f"Hello, {name}")

Generate numbers with range

range(stop) starts at zero and excludes the stop value. It also accepts start and step arguments.

for number in range(1, 6):
    print(number)

for even in range(0, 10, 2):
    print(even)

Repeat with while

A while loop continues while its condition remains true. Update state in the loop so it can finish.

countdown = 3
while countdown > 0:
    print(countdown)
    countdown -= 1
print("Go!")

Keep an index with enumerate

enumerate() provides each item and its position without manually maintaining a counter.

topics = ["strings", "lists", "loops"]
for position, topic in enumerate(topics, start=1):
    print(position, topic)