0
About the Python 3 tutorial (continue)
Hello everyone, I have some difficulties in understanding the tutorial example: i = 0 while True: i = i +1 if i == 2: print("Skipping 2") continue if i == 5: print("Breaking") break print(i) print("Finished") and the answer is : >>> 1 Skipping 2 3 4 Breaking Finished >>> I remember that for the if statement, the first one has to be true for the second one to run, but why the program still can run normally? And why if we remove the "continue", the result in python shown will only be : Skipping 2 2 Finished I am confused about the concepts, would there be anyone can help me out? (I am sorry for my bad english orz)
3 Answers
+ 3
A loop executes the same code over and over, line by line (usually with something slightly changing, like a value).
As soon as you reach a 'continue' within one run of that loop, the execution jumps directly back to the first line and starts over.
In this specific loop, this only happens if i equals 2 (otherwise the code below 'continue' would be quite useless).
'break' stops that loop completely, code continues below the block of the loop.
Try to think this through, line by line, again. Does it make more sense now?
+ 2
Exactly.
Only the indented part belongs to the if - the rest is part of the while loop, as it's indented to the same place.
If indentation is still confusing, you can read (not run!) this:
https://code.sololearn.com/cT5BRIbkia21/?ref=app
+ 1
Thank you for your explanation about continue :D I understand it now
But may I ask why the program does print out every value even the two "if" conditions is not satisfied? Is it because the "print(i)" does not belong to the if loops?