For Loop vs While Loop in Python

When I first started coding in Python, one of the biggest questions I had was: When should I use a for loop, and when should I use a while loop?

At first, both loops seem to do the same thing – repeat a block of code. But over the years, I’ve realized that choosing the right loop can make your code cleaner, faster, and easier to understand.

In this tutorial, I’ll walk you through the differences between for loops and while loops in Python. I’ll also share examples that I’ve personally used in real-world projects, so you can see exactly how each loop works in practice.

What is a For Loop in Python?

A for loop in Python is used when you know in advance how many times you want to repeat an action. It iterates over a sequence (like a list, tuple, dictionary, string, or range).

Think of it as: “Do this for every item in this collection.”

Example: Iterate Over a List of States

Let’s say I want to loop through a list of U.S. states where my company has offices.

states = ["California", "Texas", "New York", "Florida", "Illinois"]

print("Company offices are located in:")
for state in states:
    print(state)

Output:

Company offices are located in:
California
Texas
New York
Florida
Illinois

Here, the loop automatically goes through each state in the list without me worrying about counters or conditions.

What is a While Loop in Python?

A while loop is used when you don’t know in advance how many times you need to repeat something. Instead, it runs as long as a condition is True.

Think of it as: “Keep doing this until the condition is no longer true.”

Example: Count Until a Limit

Suppose I want to keep track of how many customers walk into a store until we reach 10 customers.

count = 0

while count < 10:
    count += 1
    print(f"Customer {count} entered the store.")

Output (shortened):

Customer 1 entered the store.
Customer 2 entered the store.
...
Customer 10 entered the store.

Here, I didn’t know the exact loop length in advance. The loop stopped only when the condition (count < 10) became false.

Key Differences Between For Loop and While Loop

FeatureFor LoopWhile Loop
Use CaseWhen you know the number of iterationsWhen iterations depend on a condition
ControlIterates over sequences (range, list, etc.)Runs until condition becomes False
InitializationUsually not required (handled by sequence)Manual initialization required
Best ForData iteration, fixed repetitionsIndefinite loops, waiting for conditions

Method 1 – Use For Loop with range()

Python’s range() function is one of the most common ways I use a for loop. It’s perfect when I know exactly how many times I want to repeat something.

# Print first 5 even numbers
for num in range(2, 12, 2):
    print(num)

I executed the above example code and added the screenshot below.

for loop flowchart in python

Here, range(2, 12, 2) starts at 2, goes up to (but not including) 12, and increments by 2.

Method 2 – Use While Loop for User Input

A while loop is great when I want to keep asking for input until the user provides the correct answer.

password = "PythonRocks"
user_input = ""

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

print("Access granted!")

I executed the above example code and added the screenshot below.

python for loop flowchart

This loop will keep running until the user types the correct password.

Method 3 – Combine For and While Loops

Sometimes, I use both loops together. For example, when processing customer orders where I know the number of orders (for loop), but I also want to keep retrying payment until it succeeds (while loop).

orders = ["Order#1001", "Order#1002", "Order#1003"]

for order in orders:
    print(f"Processing {order}...")

    payment_success = False
    attempts = 0

    while not payment_success and attempts < 3:
        attempts += 1
        print(f"  Attempt {attempts}: Trying payment...")

        # Simulate success on 2nd attempt
        if attempts == 2:
            payment_success = True
            print("  Payment successful!")
        else:
            print("  Payment failed. Retrying...")

I executed the above example code and added the screenshot below.

for loop in python flowchart

This is a real-world type of scenario where both loops shine in different ways.

When Should You Use For vs While?

  • Use a for loop when you know the number of iterations (looping over a list, range, or dictionary).
  • Use a while loop when the number of iterations is unknown and depends on a condition (like waiting for user input or monitoring a process).
  • If you ever find yourself writing a while loop with a counter that behaves like for i in range(...), that’s usually a sign you should switch to a for loop.

Both for loops and while loops are essential tools in Python. Over the years, I’ve learned that the choice depends on whether I know the number of iterations in advance or not.

If you’re just starting, practice with both. Try looping through lists, reading user input, or simulating real-world scenarios like payment retries or customer tracking. The more you use them, the more natural the choice will become.

You may like to read:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.