How to convert a Python for loop to while loop?


Unlike while loop, for loop in Python doesn't need a counting variable to keep count of number of iterations. Hence, to convert a for loop into equivalent while loop, this fact must be taken into consideration.

Following is a simple for loop that traverses over a range

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

To convert into a while loop, we initialize a counting variable to 0 before the loop begins and increment it by 1 in every iteration as long as it is less than 5

x=0
while x<5:
     x=x+1
     print (x)

Updated on: 11-Feb-2020

7K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements