0
After printing "Breaking" why doesn't it print the value of (i) even though in the code it is written print(i)?
i = 0 while 1==1: print(i) i = i + 1 if i >= 5: print("Breaking") break print("Finished")
3 Respostas
+ 5
Because of the sequence of executing different commands. Step 1. print(i) Step 2. i = i + 1 Step 3. if i >= 5: Step 4. break The "print(i)" command is actually executed. However, when the program displays "i", its value is still 4 (see Step 1). After executing "print(i)", as a second step, there is another command, that sets i to "i + 1", so 4 + 1, which is 5 (see Step 2). After it, the if-statement that says "if i <= 5" which so far was False, now returns a True (Step 3), so the nested break command is executed (Step 4). To sum it up, in the overall loop, there are two different values for "i": the "print(i)" command is printing out "i" before it is becoming "i+1" and this is why it looks like as if the "print(i)" has not been executed. Was it helpful for you?
+ 1
Break always exits a loop
Use "True" instead of "1==1"
If you want the " 5" to be printed, increment before print.
0
@yashil : if you increment before print, you will print 1,2,3,4,5 instead of 0,1,2,3,4. Be aware that getting 5, you loose 0...