← Back to Learn
🛑

Intermediate â€ĸ Python

Break, Continue & Nested Loops

Lesson 1 of 6
Step 1

🛑 Stopping a Loop with break

Sometimes you want a loop to stop before it has finished. The break keyword jumps out of the loop straight away. This is handy when you have found what you were looking for and do not need to keep going.

🐍 Python
for number in range(1, 10):
    if number == 5:
        print("Found 5! Stopping.")
        break
    print(number)
â–ļ Output
1
2
3
4
Found 5! Stopping.
⭐ Earn 10 XP

📚 Everything in Break, Continue & Nested Loops

Take control of your loops! Learn how to stop a loop early, skip steps, put loops inside loops to draw patterns, loop over strings, and keep running totals. Here is every step in this topic in one place, so you can review what you learned or jump straight to a step.

  1. 🛑 Stopping a Loop with break

    Sometimes you want a loop to stop before it has finished. The break keyword jumps out of the loop straight away. This is handy when you have found what you were looking for and do not need to keep going.

    for number in range(1, 10):
        if number == 5:
            print("Found 5! Stopping.")
            break
        print(number)
  2. â­ī¸ Skipping Steps with continue

    The continue keyword skips the rest of the current turn of the loop and jumps to the next one. The loop keeps going, it just ignores that one step. Here we skip the number 3.

    for number in range(1, 6):
        if number == 3:
            continue
        print(number)
  3. 🔁 Loops Inside Loops

    A nested loop is a loop inside another loop. For every single turn of the outer loop, the inner loop runs all the way through. This is useful for things like grids, tables, and games with rows and columns.

    for row in range(1, 3):
        for col in range(1, 4):
            print(f"Row {row}, Seat {col}")
  4. ⭐ Drawing a Star Triangle

    Nested loops can draw cool patterns! The outer loop picks which row we are on, and the inner loop prints that many stars. Using end="" keeps the stars on the same line, and an empty print() moves to the next line.

    for row in range(1, 5):
        for star in range(row):
            print("*", end="")
        print()
  5. 🔤 Looping Over a String

    A for loop can go through a string one letter at a time. Each time around the loop, the variable holds the next letter. This lets you check or change each letter in a word.

    for letter in "CODE":
        print(letter)
  6. 🧮 Counters and Running Totals

    A counter is a variable that goes up by 1 each time something happens. A running total (also called an accumulator) is a variable that adds up numbers as the loop goes. Start them at 0 before the loop, then update them inside it.

    total = 0
    vowels = 0
    
    for n in range(1, 6):
        total = total + n
    print("Total:", total)
    
    for letter in "banana":
        if letter in "aeiou":
            vowels = vowels + 1
    print("Vowels:", vowels)