- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- 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?
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)
Advertisements