What is a for loop vs a while loop? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

What is a for loop vs a while loop?

14th Sep 2016, 11:07 AM
Giovanni
6 Answers
+ 9
for loop is executed for a number of time >>> for x in range(10): ...... print("hello 10 times") Python has this nice kind of loop >>> a = "john","jim","sara" >>> for names in a: ....... print(names) John Jim Sara The while loop repeat itself until a condition is true n = 0 while n<10: print(n) This will go on forever, to put an end to this I must write n = 0 while n<10: print(n) n += 1 This way the n increment each time the while loop runs and when n becomes equal to ten tne condition is untrue, so it stops
14th Sep 2016, 5:21 PM
Giovanni Gatto
Giovanni Gatto - avatar
+ 2
In for loop user can set both upper and lower limit but in while loop either of them is used.
12th Nov 2016, 3:52 PM
SHUBHAM TAKBHATE
SHUBHAM TAKBHATE - avatar
+ 2
See the while loop as a more detailed version of the for loop. You can manipulate the iteration more manually in the while loop, where there is a given range by the for loop. for example: for i in range(1, 11): Here the forloop is activated when python passes by this line, here you can't really manipulate the iteration. Because the index will keep itself by the range (it is dependant on the range), so if you say: if i == 5: i = 10 Where i is gonna get the value 10 on the 5th iteration, but on the next one it is going to be 6 again. On the other hand the while loop does NOT activate automatically when python passes by a while statemant. It first checks if the boolean expression is true that is written next to the while. And it exits the loop if and only if: - the boolean expression turns into False - or when python passes by the 'break' keyword. (- or the program will stop when it encounters an error) So, here the loop will end when x == 5 (it will iterate 4 times and on the 5th iteration it will break the loop): x = 1 while True: if x == 5: break x += 1 In other words you can call the for loop a shorter version of the while loop where the iteration is being made automatically for a given range.
13th Nov 2016, 1:06 PM
EagleEye
EagleEye - avatar
+ 1
thanks!
14th Sep 2016, 9:57 PM
Giovanni
+ 1
for loop is repeated for a number of times,while while loop is repeated until a certain condition is met
25th Dec 2016, 3:33 PM
Argwings Mutuli
Argwings Mutuli - avatar
0
hjsjd
12th Nov 2016, 6:10 PM
sam
sam - avatar