I understand that loops are an integral part of any programming language. They help us to iterate tasks that are repetitive. But I don’t seem to understand why these 2 loops are required seperately. Can’t just one of them do the job? I have tried both loops and still can’t seem to understand how are these 2 loops different and where it is better to use which loop ! Please someone explain to me in detail with example!
I have tried many programs like factorial, sum of a list and prime numbers, using both loops but I’m unable to understand where to use which loop because surely there must be some rule of thumb to decide where to use which loop ! I expect someone to clear this query of mine with example.
>Solution :
There is usually not a question. If you need to run a fixed number of loops, or you need to do something once for each item in a collection, then you want a for loop. Anything based on a counter uses a for loop. If you need to loop until some specific condition happens, or loop forever, then you want a while.
# Print 5 numbers.
for i in range(5):
print(i)
It’s usually obvious when you’ve made the wrong choice:
i = 0
while i < 5:
print(i)
i += 1
That’s a lot of extra typing to do what the for loop does.
lst = [5,4,3,2,1]
for n in lst:
print("This element is",n)
But here is a case where while is better:
while True:
s = input("Type q to quit: ")
if s == 'q':
break