DEV Community

Shahrouz Nikseresht
Shahrouz Nikseresht

Posted on

Python Loops Explained: for vs while (Beginner Guide)

Loops allow your code to repeat tasks automatically. Python has two main types of loops: for and while. Each is useful in different situations.

What is a loop?

A loop runs a block of code multiple times. This avoids writing the same code over and over.

Like conditional statements, loops require a colon : and proper indentation to define the code block.

The for loop

A for loop is best when you know how many times to repeat or when working with a sequence (like a list or range).

Use range() to loop a specific number of times:

for i in range(5):
    print(i)
Enter fullscreen mode Exit fullscreen mode

This prints:

0
1
2
3
4
Enter fullscreen mode Exit fullscreen mode

Loop over a list:

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

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

The for loop is safe because it stops automatically when the sequence ends.

The while loop

A while loop repeats as long as a condition is True.

count = 0

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

This prints the same numbers: 0 to 4.

Always update the condition inside the loop (here, count = count + 1). Forgetting this creates an infinite loop that never stops.

When to use for vs while

  • Use for when you know the number of repetitions or have a sequence to iterate over. It is simpler and safer.
  • Use while when the number of repetitions depends on a condition that might change during the loop.

Using break to exit early

Both loops support break to stop early:

for i in range(10):
    if i == 5:
        break
    print(i)
Enter fullscreen mode Exit fullscreen mode

This prints 0 to 4 and then stops.

Common examples

Print even numbers from 0 to 10 with a for loop:

for i in range(0, 11, 2):
    print(i)
Enter fullscreen mode Exit fullscreen mode

Simple countdown with while:

n = 5

while n > 0:
    print(n)
    n = n - 1
print("Done!")
Enter fullscreen mode Exit fullscreen mode

Important notes

  • Indentation defines the loop body.
  • for loops are less likely to create infinite loops.
  • Always plan how the loop will end when using while.

Quick summary

  • for loops are great for known sequences or counts.
  • while loops continue based on a condition.
  • Use break to exit a loop early.
  • Proper planning prevents infinite loops.

Practice both types with small examples. Loops are essential for handling repetition in Python programs.

Top comments (0)