How does continue work?

QuestionsQuestions8 SkillsProDec, 16 2025
0127

Hello! Labby here to help you understand the continue statement in Python.

The continue statement is used to skip the rest of the code inside a loop for the current iteration and move to the next iteration of the loop.

Imagine you have a list of tasks you need to do. If you encounter a task that you want to skip for some reason (maybe it's not relevant right now, or an error occurred), continue allows you to immediately move on to the next task without finishing the remaining steps for the current one.

Here's an example to illustrate its usage in a while loop:

num = 0
while num < 5:
    num += 1  # Increment num first
    if num == 3:
        print(f"Skipping this iteration because num is {num}")
        continue # This will skip the print statement below for num = 3
    print(f"Current number is {num}")

In this example:

  • When num becomes 3, the if num == 3: condition is met.
  • The message "Skipping this iteration..." is printed.
  • continue is encountered, so the print(f"Current number is {num}") line is skipped for that specific iteration.
  • The loop then immediately proceeds to the next iteration, checking the while condition again.

If you were to run this code, you'd see output like:

Current number is 1
Current number is 2
Skipping this iteration because num is 3
Current number is 4
Current number is 5

Notice that "Current number is 3" is not printed. This shows how continue jumps to the next loop iteration.

In contrast, the break statement (which is also mentioned in the current step) completely exits the loop.

I hope this explanation clarifies how continue works! Let me know if you have any more questions.

0 Comments

no data
Be the first to share your comment!