Python - How to convert this while loop to for loop?

Converting a while loop to a for loop in Python can be achieved using itertools.count() which creates an infinite iterator. This is particularly useful when you need to iterate indefinitely until a specific condition is met.

Understanding itertools.count()

The count() function from the itertools module generates an iterator of evenly spaced values. It takes two optional parameters:

  • start ? Starting value (default is 0)
  • step ? Step size between values (default is 1)

Using default parameters creates an infinite iterator, so you must use break to terminate the loop when needed.

Example: Converting While Loop to For Loop

Here's how to use itertools.count() to replace a while loop that collects user input until they choose to stop ?

import itertools

percent_numbers = []

for x in itertools.count():
    num = input("Enter the mark: ")
    num = float(num)
    percent_numbers.append(num)
    finish = input("Stop? (y/n): ")
    if finish == 'y':
        break

print("Collected marks:", percent_numbers)
Enter the mark: 85.5
Stop? (y/n): n
Enter the mark: 92.0
Stop? (y/n): n
Enter the mark: 78.5
Stop? (y/n): y
Collected marks: [85.5, 92.0, 78.5]

Equivalent While Loop

The above for loop is equivalent to this while loop ?

percent_numbers = []
x = 0

while True:
    num = input("Enter the mark: ")
    num = float(num)
    percent_numbers.append(num)
    finish = input("Stop? (y/n): ")
    if finish == 'y':
        break
    x += 1

print("Collected marks:", percent_numbers)

Using count() with Custom Parameters

You can also use count() with custom start and step values ?

import itertools

# Start from 1, increment by 2 each time
for x in itertools.count(1, 2):
    print(f"Iteration {x}")
    if x > 10:
        break
Iteration 1
Iteration 3
Iteration 5
Iteration 7
Iteration 9
Iteration 11

Conclusion

Using itertools.count() provides an elegant way to convert while loops to for loops when you need infinite iteration with a break condition. This approach is more Pythonic and clearly expresses the intent of indefinite iteration.

Updated on: 2026-03-24T20:47:24+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements