+ 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?
2 ответов
+ 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.
+ 4
While loop is used for condition whereas forloop is used in case of sequence.