Thanks to visit codestin.com
Credit goes to www.tutorialspoint.com

Convert Python For Loop to While Loop



Converting a for loop to a while loop in Python means rewriting the loop logic in a different way to perform the same task.

While loop gives better control over conditions and is also useful for cases when the number of iterations is not fixed and depends on runtime values. Therefore, sometimes while is preferred over a for loop when the loop's continuation depends on dynamic conditions.

For Loop Code

Here is the following simple for loop that traverses over a range.

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

Output

0
1
2
3
4

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.

While Loop Code

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

Output

0
1
2
3
4

Real-World Use Case

Here is the following real-world use case example of the while loop.

password = "Tutorials321"  # Already given input

if password != "Tutorials123":
    print("Incorrect. Try again.")
    password = "Tutorials123"  # This will set correct password

print("Access granted!")

Output

Incorrect. Try again.
Access granted!

Explanation

  • The initial password Tutorials321 is not equal to the password (Tutorials123) already fed into the system; therefore loop prints "Incorrect. Try again."
  • password = "Tutorials123", this will update the current password and print Access granted!
Updated on: 2025-04-22T17:21:10+05:30

10K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements