0
What is the main difference between while and for loop?
4 Answers
+ 5
Main difference lies in its SYNTAX.
Both are used for iteration...
+ 5
In General the difference is:
> for loop is mostly used when the number of iterations are known before starting
iteration. This could be like:
- for num in range(1,10):
- for val in [1,3,7,2]:
There is loop variable, that get a defined value in each iteration. for loops can have a break or a continue statement.
> while loop is used mostly when the number of iterations is not clear when starting the loop. This could be:
- while True:
- while count <= 50:
- while x <= len(inp_values):
A loop or counter (or other variables) can be used, variables has to be incremented or decremented by code. while loops can have a break or a continue statement.
+ 2
They both are loops and have the same purpose: Repeating.
while loop is simple: If the condition is true, repeat the code. With syntax while(condition) {}
for loop expend more: You first evaluate an expression "once". Then you check the condition. Repeat the code if it's true. After every loop you evaluate another expression. With syntax for(expression_to_do_first ; condition ; expression_after_each_loops)
+ 1
While is mainly used with one variable .
But for is used with iterators where you can do any thing with each value of iterators.