continue
stops the current iteration of the loop and goes immediately to the next iteration of the loop, skipping over the remainder of the loop body.
In your while
loop, the rest of the body includes the statement x += 1
. So x
never becomes 3
, it stays at 2
. From then on, the if x == 2:
test always succeeds, and it keeps skipping over the increment, and gets stuck repeating that loop over and over.
In a for
loop, it skips over the remainder of the loop body, and then gets the next item from the iterator that it's looping over. If you changed your loop to:
for x in range(5):
if x == 2:
continue
print(x)
You would get the output that you were expecting. Incrementing x
is not done in the loop body, it's done by the for
statement itself. It happens automatically at the beginning of each iteration. So continue
only skips over the print
statement.