Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

What's the exact distinction between the FOR loop and the WHILE Loop

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading