Python language basics 63: jump over an iteration with continue

Introduction

In the previous post we looked the finally keyword. We discussed how it could be used to write a code block which is executed whether or not the code within the try-block threw an exception.

In this post we’ll look at another Python keyword which helps you jump over an iteration in case you don’t want to handle the current value in the loop in any way.

There are cases where you simply don’t want to handle certain values while iterating over a collection. The for-each block will be executed for each element in the collection but for some of them this logic should not be executed.

You can easily solve this with if-else block(s), but there’s another solution.

Continue

The continue keyword will stop the execution of the for-each block. Execution will jump back to the beginning of the loop and take the next value in the collection. This keyword exists in other popular languages such as Java or C# and it works in exactly the same way in Python.

The following code checks if the current value in the loop is even. The ‘%’ operand returns the remainder from a division. If the value is even then we print a message and then ignore the rest of the code. Otherwise we print another message for odd numbers:

integers = [1, 2, 5, 3, 6, 10, 5, 6]
for i in integers:
    if i % 2 == 0:
        print('Jumping over iteration')
        continue
    print('Printing ', i)

Here’s the output:

Printing 1
Jumping over iteration
Printing 5
Printing 3
Jumping over iteration
Jumping over iteration
Printing 5
Jumping over iteration

Read the next post here.

Read all Python-related posts on this blog here.

Advertisement

About Andras Nemes
I'm a .NET/Java developer living and working in Stockholm, Sweden.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Elliot Balynn's Blog

A directory of wonderful thoughts

Software Engineering

Web development

Disparate Opinions

Various tidbits

chsakell's Blog

WEB APPLICATION DEVELOPMENT TUTORIALS WITH OPEN-SOURCE PROJECTS

Once Upon a Camayoc

Bite-size insight on Cyber Security for the not too technical.

%d bloggers like this: