Last answered:

22 Feb 2022

Posted on:

22 Feb 2022

0

Resolved: Which loop is more effecient?

Hi !
I have a doubt which one is a better loop between for and while.
From my understanding , while loop have to do two things, check for condition and also increment or decrement the value to avoid infinite loop.
Does it mean, while loop takes more execution time?

1 answers ( 1 marked as helpful)
Instructor
Posted on:

22 Feb 2022

2

Hey,

Thank you for your question!

The choice would largely depend on the problem you have at hand.

Whenever your solution involves iterating over a range of values, then for-loops are certainly preferable. That is because you
1. set a starting value,
2. set an end value, and
3. perform the iteration
all in one line:

for i in range(start, end):
    ...

where start and end are arbitrary integers. In a while-loop, on the other hand, you would need a separate line for each of these operations:

i = start
while i < end:
    ...
    i += 1

where I have assumed start < end. Therefore, not only would a for-loop perform more efficiently, but would also increase readability and make your code tidier, which is a great advantage! for-loops also avoid the possibility of entering an infinite loop by forgetting to increment the value of your iterator, as might happen in a while-loop.

Consider now the example that Giles gives in the lesson, where a teacher needs to enter the ages of all class members from all classes. A for-loop would not be appropriate here because the number of students from each class might not be the same. In a while-loop, the teacher inputs the ages until -1 is entered which would exit the loop and indicate that there are no more student in that class.

I hope this answers your question!

Kind regards,
365 Hristina

Submit an answer