DEV Community

Cover image for Python Loops Explained: for Loop vs while Loop with Simple Examples
Lavkush kumar
Lavkush kumar

Posted on Originally published at codingcush.com

Python Loops Explained: for Loop vs while Loop with Simple Examples

Originally published on CodingCush.

A loop lets you repeat a block of code instead of copying and pasting it over and over. Python gives you two loops. A for loop repeats once for each item in a collection — each letter in a word, each number in a range, each name in a list. A while loop keeps repeating as long as a condition stays true. The simple rule is this: use for when you know what you are walking through, and while when you only know the rule for stopping. Almost every loop you will ever write in Python is one of these two, so let us make both of them feel easy.

Why do loops matter so much? Imagine printing the numbers 1 to 100 without one: you would write 100 lines, and printing 1 to 1,000 would take 1,000 lines. With a loop, the same job takes three lines and works just as well for a million numbers. Loops are also where beginners hit their first funny bug — the infinite loop, a program that runs forever because the stopping condition never becomes false. We will show you exactly how that happens, and how to avoid it, because every Python programmer has done it at least once.

The for Loop: One Round Per Item

The for loop is Python's friendliest loop. You give it a collection, and it hands you one item at a time. Here it is walking through a list of names:

fruits = ["apple", "banana", "cherry"]

for fruit in fruits:
    print(fruit)
Enter fullscreen mode Exit fullscreen mode

That prints apple, banana and cherry, one per line. There is no counter for you to manage and nothing to forget — the loop simply stops when the list runs out. The same idea works on strings, because a string is a collection of characters:

for letter in "cat":
    print(letter)
Enter fullscreen mode Exit fullscreen mode

When you need plain counting, Python gives you range(), which produces a sequence of numbers. range(5) gives 0, 1, 2, 3, 4 — note that it starts at 0 and stops one before the number you pass. This catches everyone at first, so say it out loud once: range goes up to, but does not include, its ending number. The Python documentation's control flow chapter covers for and range() in friendly detail with runnable examples in the official Python tutorial on control flow.

for i in range(1, 6):
    print("Number:", i)
Enter fullscreen mode Exit fullscreen mode

Here range(1, 6) starts at 1 and stops before 6, so you get a tidy count from 1 to 5. You can even add a step: range(0, 10, 2) gives the even numbers 0, 2, 4, 6, 8. Clean, readable, and very hard to break — which is why for is the loop you will reach for most often.

The while Loop: Repeat Until the Condition Says Stop

A while loop does not walk through a collection. It checks a condition, runs the block if the condition is true, then checks again. The moment the condition becomes false, the loop ends. Here is a simple countdown:

count = 5

while count > 0:
    print(count)
    count = count - 1

print("Lift off!")
Enter fullscreen mode Exit fullscreen mode

The single most important line there is count = count - 1, inside the loop. Without it, count stays at 5 forever, the condition stays true forever, and your program counts down to nothing — literally, it just prints 5 until you kill it. That is the famous infinite loop. The loop itself is not dangerous; forgetting to change something inside it is. The formal definitions of both loop types, including the optional else clause on loops, live in the Python language reference on compound statements.

The while loop shines when you do not know in advance how many rounds you need. The classic example is asking for a password until the user types the right one. You cannot know if that takes one try or twelve — so a fixed-count loop cannot help, but a condition can:

password = ""

while password != "python123":
    password = input("Enter the password: ")

print("Welcome!")
Enter fullscreen mode Exit fullscreen mode

Python documentation control flow page covering for loops, range and while loops

The official Python tutorial's control flow chapter — the home of for loops, range(), break and continue, explained with examples.

The Same Task, Written Both Ways

The clearest way to feel the difference is to do one job with both loops. Let us print the numbers 1 to 5. First, the for version:

for i in range(1, 6):
    print(i)
Enter fullscreen mode Exit fullscreen mode

Now the same job with while:

i = 1

while i <= 5:
    print(i)
    i = i + 1
Enter fullscreen mode Exit fullscreen mode

Both print exactly the same output. But look at the shape: the for version is two lines and there is nothing to forget. The while version needs you to set up the counter before the loop, write the condition yourself, and remember to increase the counter inside. Three chances to make a mistake instead of zero. That is the whole lesson: if a for loop can do the job, let it. Save while for the jobs where the stopping rule is a condition, not a collection.

for vs while: The Side-by-Side Table

Point for loop while loop
Repeats based on Items in a collection or range A condition staying true
Number of rounds Known, or fixed by the collection Unknown — depends on the condition
Counter management Automatic You manage it yourself
Risk of infinite loop Almost none Real — if the condition never changes
Best for Lists, strings, files, counting Waiting for input, retries, games
Typical shape for item in collection: while condition:

break and continue: Two Useful Escape Hatches

Both loops share two handy keywords. break stops the loop completely, right now. continue skips the rest of the current round and jumps to the next one. Searching a list is the classic break job — once you find what you were looking for, there is no point checking the rest:

names = ["Asha", "Rahul", "Meena", "Kiran"]

for name in names:
    if name == "Meena":
        print("Found Meena!")
        break
Enter fullscreen mode Exit fullscreen mode

And continue is perfect for skipping items you do not want to process, like printing only the odd numbers from 1 to 10 by skipping the even ones. These two keywords work in both loops and turn clumsy flag variables into short, honest code.

Common Beginner Mistakes

Mistake one: the infinite while loop, already covered — something inside the loop must move you closer to the condition becoming false, every single round. Mistake two: expecting range(5) to include 5. It does not; it stops at 4. When your loop feels one short, this is almost always why. Mistake three: changing a list while looping over it — removing items as you go confuses the loop's position, so build a new list instead. Mistake four: using a while loop with a manual counter to walk through a list, when a simple for loop would do it in one line with nothing to get wrong.

Once loops feel comfortable, the natural next step is grouping code into reusable pieces and modelling real things — our guide to Python Classes and Objects, Explained Simply builds directly on this. And loops become truly powerful when they read real data: How to Read and Write Files in Python shows the classic pattern of looping through every line of a file, which is one of the most useful tricks in the whole language.

Frequently Asked Questions

Which loop should a beginner learn first?

The for loop. It is safer, shorter, and covers most everyday jobs — walking through lists, strings, ranges and files. Learn while right after, for condition-based repetition.

Can a while loop do everything a for loop can?

Technically yes — any for loop can be rewritten with while and a manual counter. But the rewrite is longer and easier to break, so prefer for whenever you are walking through a collection.

How do I stop an infinite loop?

Press Ctrl + C in the terminal to stop the program. Then fix the cause: make sure something inside the loop changes the values in the condition, so it eventually becomes false.

What does range() actually return?

An immutable sequence of numbers, produced lazily as the loop needs them. range(3) means 0, 1, 2 — start included, stop excluded, step 1 unless you say otherwise.

Conclusion

Loops are the difference between writing a program and writing a program that does real work. Use for when you are walking through something — a list, a string, a range, a file — and use while when you are waiting for a condition to change. Keep the infinite-loop rule taped to your monitor: something inside a while loop must change, every round. Write both versions of the 1-to-5 counting program once with your own hands, and the choice between the two loops will never puzzle you again.

Top comments (0)