+ 3

In Python what are the things that 'while loop' can do but can't be done by 'for loop '? Are there any such things?

31st Oct 2018, 5:15 PM
Sai Sudheer
Sai Sudheer - avatar
2 Réponses
+ 5
In Python, for loops are a bit restrictive in the sense that they require something to iterate over: list, string, tuple, range, set, dictionary key, generator, etc. When we don't have such things, or we don't really have a way of telling after how many steps the loop will stop, we resort to while loops. An example: while True: ans = input("Do you like spam and eggs (Y/N)? ") if ans == 'Y': break Here, we don't know apriori how long the user would take to realize that 'Y' is the only legitimate answer. 😉 Note. There are roundabout ways of doing this with for loops too (using itertools.count), but while is the better choice here.
31st Oct 2018, 6:19 PM
Kishalaya Saha
Kishalaya Saha - avatar
+ 4
While loop is used for condition whereas forloop is used in case of sequence.
1st Nov 2018, 1:54 AM
Ayush Sinha
Ayush Sinha - avatar