Skip to content
Home » The continue Statement in Python

The continue Statement in Python

Spread the love

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.

Your Panda3D Magazine

Make Awesome Games and Other 3D Apps

with Panda3D and Blender using Python.

Cool stuff, easy to follow articles.

Get the magazine here (PDF).

Python Jumpstart Course

Learn the basics of Python, including OOP.

with lots of exercises, easy to follow

The course is available on Udemy.

Blender Jumpstart Course

Learn the basics of 3D modeling in Blender.

step-by-step, easy to follow, visually rich

The course is available on Udemy and on Skillshare.


Spread the love

Leave a Reply