 
  Data Structure Data Structure
 Networking Networking
 RDBMS RDBMS
 Operating System Operating System
 Java Java
 MS Excel MS Excel
 iOS iOS
 HTML HTML
 CSS CSS
 Android Android
 Python Python
 C Programming C Programming
 C++ C++
 C# C#
 MongoDB MongoDB
 MySQL MySQL
 Javascript Javascript
 PHP PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to convert a 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!
Advertisements
 