+ 1
0,1,2,3,4,Breaking,finished
i = 0
while 1==1:
print(i)
i = i + 1
if i >= 5:
print("Breaking")
break
print("Finished")
Run again
+ 1
https://code.sololearn.com/cBy69SdH8Rw8/?ref=app
What is the problem man
+ 1
While loops run endlessly until we break out. (or condition become false)
here i = 0
while 1==1 (Always true):
print(i) -- (Print the value of i .Right now it's 0)
i = i + 1 ---(increse i by 1 every time )
if i > 5 : --(This loops gonna stop at 5 )
print('Breaking')
break
When loops reach end it's going to run again until it becomes false or read break statement.
so it's gonna print 0,1,2,3,4 and at 5 its gonna break out because of if statement.
But the whole point is while loops run again and again until it breaks or becomes false.
I hope you understand (if not be sure to check while loop theory you will def. understand. I tried my best to mention it below)
let's say we have a loop -
i = 0
while i <3 :
print (i)
i += 1
if i == 2 :
break
This loop run like this --
First its gonna print 0 then add 1 to i (i.e. i = 1)
NOW, is i == 2 NO so if stat wont gonna run
Now we reach at the end of the loops but we won't break out as condition is true (i.e. i = 1 which is less than 3)
Again its gonna run similarly until we get i == 2
then if statement gonna run and loop gonna break out.(i.e.STOP)
Be clear with concepts and then practice on that concept you will become good at this .
I Hope You Understand. If you have any queries feel free to ask. Happy Coding.
0
while 1==1 is equivalent to : while true.
i is incremented until it equals 5 and breaks.
what didn't you understand exactly?
why did you write everything in title?
0
output is 0, 1, 2, 3, 4, Breaking, Finished...
first iteration:
print 0 (initial value of i)
then increase i by 1 (i == 1)
continue because i<5
2nd iteration:
print 1 (actual valie of i)
i = i+1 (2)
continue because i<5
3rd iteration:
print 2
i = i+1 (3)
continue because i<5
4th iteration:
print 3
i = i+1 (== 4)
continue because i<5
5th iteration:
print 4
i = i+1 (== 5)
print "Breaking" and stop loop (break) because i==5
out of the loop, print "Finished"