+ 2

How does this loop work?

i = 0 while i < 5: i +=1 if i == 3 break else: print(0)

24th Oct 2018, 6:58 AM
AMAN TOMAR
AMAN TOMAR - avatar
6 Answers
24th Oct 2018, 7:34 AM
AMAN TOMAR
AMAN TOMAR - avatar
+ 2
ABDUL MANAN thank you
24th Oct 2018, 7:35 AM
AMAN TOMAR
AMAN TOMAR - avatar
+ 2
Actually it prints 0 only two times, because loop checks "if" condition only for 1, 2 and 3.
24th Oct 2018, 8:00 AM
Ɓukasz Ɓukaszew
Ɓukasz Ɓukaszew - avatar
+ 1
While loop checks if i variable is smaller than 5. If it is True part inside the loop is being executed. For every run: 1 added to i, next checking if i is equal 3, if it's not then 0 is printed from the "else" statement. When i is finally equal 3 then loop stops because of "break".
24th Oct 2018, 7:29 AM
Ɓukasz Ɓukaszew
Ɓukasz Ɓukaszew - avatar
+ 1
It will print 000 i.e three times 0, because at first i=0 which means less than 3 so it will print 0. Next i will be incremented to 1 and will print 0 till i==2. But when i==3 or greater than 2, it will come out of the loop and stop print command. So the code allows to print 0 three times.
24th Oct 2018, 7:32 AM
ABDUL MANAN
ABDUL MANAN - avatar