I dont get this | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

I dont get this

i=0 while 1==1 print (i) i=i+1 if i>=5: print ("breaking") break print ("finished") what i dont understand is why the loop breaks after printing 4. and why not 5

31st Dec 2016, 6:18 AM
stephen haokip
stephen haokip - avatar
4 Answers
+ 2
It's difficult ( pretty imossible ) to say, because your post don't reproduce the indentation of your code ^^ It could mean: i=0 while 1==1 print (i) i=i+1 if i>=5: print ("breaking") break print ("finished") As weel as: i=0 while 1==1 print (i) i=i+1 if i>=5: print ("breaking") break print ("finished") Or: i=0 while 1==1 print (i) i=i+1 if i>=5: print ("breaking") break print ("finished") And many other variations, with differents meanings ;) ( or indentations errors )... Indentation is extremly important thing in Python, it's a part of the language syntax. If you want to be helped, please clean copy paste your code ^^
31st Dec 2016, 6:39 AM
visph
visph - avatar
+ 1
because the print statement goes after the brake statement. The loop breaks before being able to print the 5.
31st Dec 2016, 6:26 AM
Ri Wo
Ri Wo - avatar
0
lets go through each line.. i = 0 sets i to 0 while 1 == 1: (while true do the following) print i ( prints value of i) i = i + 1 (adds 1 to the previous i value and sets new value of i) if i >=5: (checks to see if new val of i is greater or equal to 5 if not it sends it back through the loop if it meets the criteria when = 5 it goes through to the break) print "breaking" break(exits the loop) print "finished" So before it can even print the value 5 it exits the loop because when i goes from 4 to 5 it meets the requirements and continues into the if statement
31st Dec 2016, 6:36 AM
Eric Reed
Eric Reed - avatar
0
dang ri is faster than me
31st Dec 2016, 6:38 AM
Eric Reed
Eric Reed - avatar