When to use for and while? It is difficult to figure out. | Sololearn: Learn to code for FREE!

+1

When to use for and while? It is difficult to figure out.

11/7/2021 11:01:38 AM

Shreya Dixit

3 Answers

New Answer

+3

use 'for' when you know how many loops and use 'while' when you don't know how many loops

+1

Usage of while loop is - when we wish to repeat some instructions a fixed number of time.. And for loop -for loop allows us to specify three things about the loop in a single line. 1.setting a loop counter to an initial value. 2.testing the loop counter to determine whether It's value has reached the number of repetitions desired. 3.increasing the value of loop counter each time the body of the loop has been executed.

0

In addition to the feedbacks you have gotten, both for loop and while loop will give you the same result. There usability however varies. Let's put it this way. Always use a For Loop whenever you want to iterate over a sequence of values. I.e, let's say you have a list or some string, and you want to remove or add or do something on the list or string, use a for loop. It will help a lot. Also learn how to use list of comprehension. Always use a while loop whenever you need to iterate a given sequence UNTIL a certain condition is met. That being said, I hope this adds up to the knowledge you have gathered.