In one of the previous articles we were talking about the break statement, which is used to control work flow inside loops. Today we’ll be talking about another such statement, the continue statement.
The continue statement works in a bit different way than the break statement. It stops the current iteration of the loop and moves on to the next iteration by checking the condition again. Let’s slightly modify the code we were using in the article about the break statement:
target = 10
guess = 0
while guess != target:
guess = int(input("Choose a number 1-20 but 6 doesn't work! "))
if guess == 6:
continue
if guess == target:
print("You win!")
else:
print("Try again!")
To make the game more exciting, we removed the possibility of quitting earlier. Instead we don’t allow the player to enter 6. If the player does enter 6, the continue statement stops the iteration and moves to the next, which means the lines of code below the continue statement in the loop are never reached. But the loop is not stopped yet, it just asks for new input in the next iteration. By the way, if the target happened to be 6, the game would be unplayable. Here’s how the output might look. Look at the line where 6 is entered:
Choose a number 1-20 but 6 doesn't work! 2
Try again!
Choose a number 1-20 but 6 doesn't work! 5
Try again!
Choose a number 1-20 but 6 doesn't work! 0
Try again!
Choose a number 1-20 but 6 doesn't work! 6
Choose a number 1-20 but 6 doesn't work! 10
You win!
The break and continue statements work in for and while loops.