Altcademy - a Forbes magazine logo Best Coding Bootcamp 2023

What is continue in Python

Understanding the 'continue' Statement in Python

When you're starting your journey in the world of programming, it's like learning a new language. You learn how to give instructions to the computer to perform tasks for you. Python, known for its simplicity and readability, is a great place to start. One of the instructions you can give in Python is continue, a statement that can alter the flow of your loops. Let's dive into what continue means and how you can use it.

The Basics of Loops

Before we understand continue, we need to talk about loops. Imagine you have a playlist of your favorite songs. A loop is like hitting the repeat button - it tells your music player to go back to the start of the playlist once it reaches the end. In programming, loops repeat a set of instructions.

In Python, the most common loops are for and while. A for loop repeats instructions a specific number of times, while a while loop continues until a certain condition is no longer true.

Enter the 'continue' Statement

Now, what if you want to skip a particular song in your playlist without stopping the whole loop? That's where continue comes into play. In Python, continue is a control statement that tells the loop to immediately stop the current iteration and move on to the next one.

How 'continue' Works

Let's see continue in action with a simple example. Imagine you're counting from 1 to 10, but you want to skip all the even numbers:

for number in range(1, 11):
    if number % 2 == 0:
        continue
    print(number)

In this code, range(1, 11) generates numbers from 1 to 10. The for loop iterates through these numbers. The if statement checks if the number is even (number % 2 == 0 - this means the remainder when the number is divided by 2 is zero). If it is even, continue is executed, which skips the print(number) statement and proceeds to the next iteration. The result is that only odd numbers are printed.

Another Example with a 'while' Loop

continue isn't limited to for loops. It works with while loops too. Let's say you're waiting for a shooting star to make a wish, but you only have until your watch hits midnight to spot one:

time = 10  # Starting time is 10 PM
while time < 12:
    time += 1
    if time == 11:
        print("Clouds blocked the sky at 11 PM.")
        continue
    print(f"Looking for a star at {time} PM.")

Here, the while loop continues to run as long as time is less than 12. If the time reaches 11 PM, the message about clouds blocking the sky is printed, and continue skips the next print statement for that iteration. The loop then goes on to the next hour.

Intuitions and Analogies

Think of continue as a polite conversation interrupter. You're in a conversation (the loop), and whenever a specific topic comes up (the condition), you gently steer the conversation away (skip the rest of the loop body) without leaving the chat (ending the loop).

Another way to visualize continue is by imagining a game of hopscotch where certain squares are marked as "skip." Each square is an iteration, and when you land on a "skip" square, you hop over it and move to the next one.

When to Use 'continue'

You might wonder why you'd want to skip part of a loop. Here are a couple of situations:

  • Filtering out values: Sometimes, you only want to process certain items from a list. Using continue, you can skip the ones you don't want.
  • Avoiding errors: If you know a certain value might cause an error, you can use continue to skip it and keep your program running smoothly.

Code Example: Filtering a List

Let's say you have a list of temperatures from various sensors, but some sensors are malfunctioning and returning -999. You want to calculate the average temperature without including these faulty readings:

temperatures = [22, 19, -999, 25, 18, -999, 20]
valid_temperatures = []
for temp in temperatures:
    if temp == -999:
        continue
    valid_temperatures.append(temp)

average_temp = sum(valid_temperatures) / len(valid_temperatures)
print(f"The average valid temperature is {average_temp}")

In this code, continue skips the -999 values, and only valid temperatures are added to the valid_temperatures list. The average is then calculated using the valid values.

Best Practices

While continue is useful, it's important not to overuse it. Too many continue statements can make your code hard to read and understand. Always aim for clarity in your code. If you find yourself using continue too often, consider if there's a more straightforward way to write your loop.

Common Pitfalls

One thing to watch out for is using continue in nested loops (a loop inside another loop). Remember that continue only affects the innermost loop. If you want to skip an iteration in an outer loop, you'll need to use a different approach.

Conclusion

In the grand symphony of programming, continue is like a skilled musician's ability to skip a beat without missing the rhythm. It allows your loops to be flexible and efficient, skipping over the unnecessary parts while keeping the melody of your code flowing. As you continue to explore the vast landscapes of Python, remember that continue is a tool that, when used judiciously, can fine-tune your loops and make your code dance to the tune of efficiency and clarity. Happy coding, and may your loops always bring you to the next exciting iteration of your programming journey!