Python Continue - Controlling for and while Loops
continue is used to skip the remainder of a loop when certain conditions are met. When called,
continue will tell Python to skip the rest of the code in a loop and move on to the next iteration.
To demonstrate, let's look at how we could use
continue to print out multiples of seven between one and fifty. Notice how the
print() statement is skipped when the
if statement is true:
continue is a control statement
for statements are fundamental in any large Python script (and a few small ones too). These statements follow a stringent set of rules predefined by Python, so we sometimes need to use what are known as control statements to influence them. The three control statements are
break, allowing you to govern your code in different manners.
More examples of
As mentioned previously,
continue is used to skip to the end of the current iteration of a loop. Therefore,
Python will only bypass code in situations that trigger
continue. For a more complex example, let's say we'd like to iterate through a list of numbers and find the square root of each number in the list. For this example, we'll use
for loop reaches minus nine, our Python script crashes. The reason that our program crashes is
math.sqrt doesn't work with negative numbers. One way of avoiding this error is by using
continue like so:
continue here means Python will skip any negative numbers, preventing us from getting a value error. The diagram below shows the process followed inside of our
continue is often used to skip error cases in Python, as it's considered more Pythonic than using an exception handler. Using
continue can often also help make large programs much more efficient. It's possible to end up with long sections of code that you only require in certain situations, so you could use
continue to skip these when suitable.
continue is an excellent way of exercising more control over your scripts, hence why it's called a control statement. Whenever
continue is triggered, it will skip to the end of whatever loop it's inside. In cases where you're working with nested loops,
continue will only cut to the end of the inner-most loop. In terms of its applications,
continue can be great for handling error cases. It's also a great way to skip past unrequired code segments, making your Python programs much more efficient.