chapter 5.1

Loops

Repeating actions with for and while

Loops let you repeat code without writing it over and over. Python has two kinds: for loops (when you know how many times) and while loops (when you don't).
for loops iterate over a sequence — a list, a string, a range of numbers:
# Loop through a range of numbers
for i in range(5):
    print(f"Count: {i}")

# range(5) gives: 0, 1, 2, 3, 4  (NOT 5!)
warning
range(5) produces 0 through 4 — five numbers, but it stops *before* 5. This trips up everyone at first. range(1, 6) gives 1 through 5.
# Loop through a list
colors = ["red", "green", "blue"]
for color in colors:
    print(f"Color: {color}")

# Loop through a string
for char in "Python":
    print(char)
while loops keep running as long as a condition is True:
countdown = 5
while countdown > 0:
    print(f"T-minus {countdown}...")
    countdown -= 1    # Same as: countdown = countdown - 1
print("Liftoff!")
warning
If you forget to update the loop variable (like countdown -= 1), the condition never becomes False and you get an infinite loop. Your program hangs forever.
break exits a loop early. continue skips to the next iteration:
# break — stop when we find it
numbers = [1, 3, 7, 12, 5, 9]
for n in numbers:
    if n > 10:
        print(f"Found {n}, stopping!")
        break
    print(f"Checked {n}")

# continue — skip odd numbers
for i in range(10):
    if i % 2 != 0:
        continue
    print(f"Even: {i}")
enumerate() gives you both the index and the value — use it instead of tracking an index manually:
fruits = ["apple", "banana", "cherry"]
for i, fruit in enumerate(fruits):
    print(f"{i}: {fruit}")
your turn
challenge

Write a loop that prints the multiplication table for the number 7 (7 x 1 = 7, 7 x 2 = 14, etc. up to 7 x 10). Use a `for` loop with `range()` and an f-string.

loading editor...

output
$ Press RUN to execute your code
AI Tutor

Ask about Loops

Hey! I'm your AI tutor.

Ask me anything about this lesson, or paste code you're stuck on.

AI tutor is a premium feature