Last modified: Oct 28, 2026

Python For Loop and While Loop Explained

Loops are essential in programming. They help repeat tasks efficiently. In Python, two main types of loops exist: the for loop and the while loop. Understanding both is crucial for writing clean and effective code.

What Is a For Loop in Python?

A for loop in Python iterates over a sequence. This sequence could be a list, tuple, string, or range. It executes a block of code for each item in the sequence.

The basic syntax of a for loop is straightforward:


for item in sequence:
    # Code to execute for each item
    print(item)

Here, item represents the current element in the sequence during each iteration.

Example: Iterating Over a List

Let’s say we have a list of fruits and want to print each one:


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

for fruit in fruits:
    print(fruit)

apple
banana
cherry

This loop prints each fruit in the list one by one.

Example: Using the Range Function

The range() function generates a sequence of numbers. It’s commonly used with for loops:


for i in range(5):
    print(i)

0
1
2
3
4

This example prints numbers from 0 to 4. Note that range(5) includes 0 but excludes 5.

What Is a While Loop in Python?

A while loop in Python repeats a block of code as long as a condition is true. Unlike the for loop, it doesn’t iterate over a sequence. Instead, it depends on a boolean condition.

The syntax of a while loop is simple:


while condition:
    # Code to execute while condition is true
    print("Loop is running")

Example: Basic While Loop

Let’s create a loop that counts from 1 to 5:


count = 1

while count <= 5:
    print(count)
    count += 1

1
2
3
4
5

In this example, the loop continues as long as count is less than or equal to 5. Each iteration increments count by 1.

Avoiding Infinite Loops

A common mistake with while loops is creating an infinite loop. This happens when the condition never becomes false:


# ❌ Bad example - infinite loop
count = 1

while count <= 5:
    print(count)
    # Forgot to increment count

This loop will run forever because count never changes. Always ensure your loop has a way to terminate.

For Loop vs While Loop: When to Use Each

Choosing between a for loop and a while loop depends on your use case.

  • Use a for loop when you know how many times to iterate or are working with a sequence.
  • Use a while loop when the number of iterations is unknown and depends on a condition.

Example: Unknown Iteration Count

If you want to ask the user for input until they type "quit", a while loop is ideal:


user_input = ""

while user_input != "quit":
    user_input = input("Type 'quit' to exit: ")
    print("You typed:", user_input)

Type 'quit' to exit: hello
You typed: hello
Type 'quit' to exit: quit
You typed: quit

This loop continues until the user types "quit".

Controlling Loop Execution

Sometimes you need more control over your loops. Python provides keywords like break and continue.

Using the Break Statement

The break statement exits a loop early:


for number in range(1, 10):
    if number == 5:
        break
    print(number)

1
2
3
4

The loop stops when number reaches 5.

Using the Continue Statement

The continue statement skips the current iteration and moves to the next one:


for number in range(1, 6):
    if number == 3:
        continue
    print(number)

1
2
4
5

Notice that 3 is skipped in the output.

Nested Loops

You can place one loop inside another. These are called nested loops.


for i in range(3):
    for j in range(2):
        print(f"i={i}, j={j}")

i=0, j=0
i=0, j=1
i=1, j=0
i=1, j=1
i=2, j=0
i=2, j=1

Nested loops are useful for working with grids or matrices.

Best Practices for Python Loops

Follow these tips for better loop performance and readability:

  • Keep loop bodies simple and focused.
  • Avoid unnecessary computations inside loops.
  • Use range() with for loops when counting.
  • Be cautious with infinite loops in while statements.

Real-World Applications

Loops are used in many real-world scenarios. For instance, when processing large datasets, you might loop through records. When building games, loops handle game ticks. When working with APIs, loops help paginate through results.

If you're working with data generation, consider generating test data with Faker in Python to simulate realistic inputs for your loops.

Loops also play a role in natural language processing tasks. For example, you might loop through sentences for tokenization with NLTK in Python to analyze text efficiently.

Additionally, when integrating with external services, loops help manage retries and batch processing. Learn more about this in OpenAI function calling in Python for advanced automation workflows.

Conclusion

Both for loops and while loops are fundamental tools in Python. Use for loops for known sequences and while loops for condition-based repetition. Mastering these concepts will make your code more powerful and flexible. Practice with different examples to build confidence. Remember to avoid infinite loops and use break and continue wisely.