0

What is the main difference between while and for loop?

15th Sep 2020, 2:16 PM
Abdullah Khan
Abdullah Khan - avatar
4 Answers
+ 5
Main difference lies in its SYNTAX. Both are used for iteration...
15th Sep 2020, 2:19 PM
Alphin K Sajan
Alphin K Sajan - avatar
+ 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.
15th Sep 2020, 5:00 PM
Lothar
Lothar - avatar
+ 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)
15th Sep 2020, 2:29 PM
äœ çŸ„é“èŠć‰‡ïŒŒæˆ‘äčŸæ˜Ż
äœ çŸ„é“èŠć‰‡ïŒŒæˆ‘äčŸæ˜Ż - avatar
+ 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.
15th Sep 2020, 2:32 PM
Divya Mohan
Divya Mohan - avatar