DEV Community

Neema Kirui
Neema Kirui

Posted on

Python Loops: Teaching Your Program to Repeat Itself (Without Repeating Yourself)

Conditionals taught your program to choose between paths. Loops teach it to do something more than once without you writing the same line over and over. This post covers for loops, while loops, break and continue, and enumerate(), the small tool that makes numbered lists genuinely easy.

1. Looping Over Things You Already Have

A for loop runs its block once for every item in something, a list, a range of numbers, even the letters in a word.

fruits = ["mango", "banana", "pineapple"]

for fruit in fruits:
    print(f"I like {fruit}")
Enter fullscreen mode Exit fullscreen mode

That prints one line per item in fruits automatically, instead of you writing print() three separate times by hand. When you just need to repeat something a set number of times rather than loop over an existing list, range() generates the numbers for you:

for i in range(5):
    print(f"Count: {i}")
Enter fullscreen mode Exit fullscreen mode

GOOD TO KNOW
range(5) counts 0, 1, 2, 3, 4, five numbers total, not 1 through 5. Python counts from zero almost everywhere, and this is one of the first places that catches people off guard.

2. When You Don't Know How Many Times, Use while

A for loop is for when you know how many times you're repeating something. A while loop is for when you don't, you just want to keep going until some condition stops being true.

balance = 100

while balance > 0:
    balance -= 20
    print(f"Balance is now {balance}")
Enter fullscreen mode Exit fullscreen mode

There's no fixed repeat count written anywhere in that loop. It just keeps subtracting until balance > 0 becomes false, then stops on its own.

GOLDEN RULE
Something inside a while loop has to actually move it toward becoming false. Forget to update the condition, and you've written an infinite loop, one of the most common ways a beginner's first program freezes solid. If your program hangs and never finishes, this is the first thing to check.

Sometimes you don't know in advance how many times something should repeat at all, you just want "keep going until the user says stop." That's while True, paired with break:

while True:
    answer = input("Type 'quit' to stop: ")
    if answer.lower() == "quit":
        break
    print(f"You typed: {answer}")
Enter fullscreen mode Exit fullscreen mode

while True never becomes false by itself, so break is the only way out. That's not a hack, it's a completely normal pattern for menus and games, anywhere "keep going until told otherwise" is exactly the behaviour you want.

3. Cutting a Loop Short: break and continue

break exits a loop immediately, skipping everything left inside it. continue skips just the current pass and moves straight to the next one, without leaving the loop entirely.

for number in range(1, 11):
    if number == 5:
        break
    print(number)
# prints 1, 2, 3, 4, then stops entirely
Enter fullscreen mode Exit fullscreen mode
for number in range(1, 11):
    if number % 2 == 0:
        continue
    print(number)
# prints only the odd numbers: 1, 3, 5, 7, 9
Enter fullscreen mode Exit fullscreen mode

COMMON BUG
break says "stop everything now." continue says "skip this one, but keep going." Mixing the two up is an easy mistake, and it usually shows up as a loop that either stops too early or never skips what you expected it to.

4. Numbering a List Without Doing the Counting Yourself

Displaying a numbered list is such a common need that Python has a built-in tool for it. Without enumerate(), you'd have to track the count yourself:

items = ["Bread", "Milk", "Eggs"]

count = 1
for item in items:
    print(f"{count}. {item}")
    count += 1
Enter fullscreen mode Exit fullscreen mode

That works, but it's more bookkeeping than the task deserves. enumerate() hands you the position and the value together, in one clean loop:

items = ["Bread", "Milk", "Eggs"]

for index, item in enumerate(items, start=1):
    print(f"{index}. {item}")
Enter fullscreen mode Exit fullscreen mode

Both print the same thing:

1. Bread
2. Milk
3. Eggs
Enter fullscreen mode Exit fullscreen mode

WHY IT MATTERS
The start=1 argument tells enumerate() to begin counting from 1 instead of its default of 0. Leave it out, and your nicely numbered menu starts at "0. Bread", which is technically correct and completely unnatural to read. Any time you're building a menu a person will actually look at, start=1 is what you want.

5. A Small Menu Program That Uses All Four

Here's everything from this post, while, for, enumerate(), and break, working together in one small menu-driven program.

snacks = ["Chips", "Chocolate", "Juice", "Crisps"]

while True:
    print("\n--- Snack Menu ---")
    for index, snack in enumerate(snacks, start=1):
        print(f"{index}. {snack}")
    print("0. Exit")

    choice = input("Enter choice: ")

    if choice == "0":
        print("Goodbye!")
        break

    if not choice.isdigit() or not (1 <= int(choice) <= len(snacks)):
        print("Invalid choice, try again.")
        continue

    print(f"You picked: {snacks[int(choice) - 1]}")
Enter fullscreen mode Exit fullscreen mode

while True keeps the menu showing up until the user chooses to leave. The for loop with enumerate() numbers the snacks freshly every time the menu prints. continue sends an invalid entry straight back to the top of the menu instead of crashing or continuing with a bad value. And break is the one clean way out, once the user actually asks to exit.

The Loop You'll End Up Using Without Even Noticing

Almost every program you've ever used has a loop in it somewhere, a feed that keeps scrolling, a game that keeps asking for input, a form that keeps validating until you get a field right. Loops are what let a program handle "I don't know how many times this needs to happen" gracefully, instead of you trying to guess and hardcode a number.

This is also usually the point where beginners hit their first real debugging wall, not because the syntax is hard, but because tracing a loop in your head takes practice. If a loop doesn't behave the way you expected, the fix is almost always the same: drop a print() inside it and watch the values change on each pass. You'll see exactly where it went off script, and that single habit will save you more time than anything else in this post.

Top comments (0)