Python

Loops in Python

In this article, we’re going to learn how to work with loops in Python.

1. Introduction

In all programming languages, loops are used to control the flow of or application. Sometimes, we use loops to iterate a list or a collection of data.

Python provides some types of loops to handle our data structures during the execution of the software.

In the next sections, we’re going to learn about these loops and how to implement them.

1.1 Pre-requisites

The examples found in this article work in version 3.6 or above. You can find the most recent version of Python here. Also, feel free to use any IDE/Code Editor with support for Python language and versions recommended above.

2. For statement

Let start with the most popular loop in the programming language’s world: for. However, in Python the for statement is a little bit different from other languages like C or Pascal, where we need to control the iterating of the collection (the famous for(int i=0; i < collection.size(); i++)).

Python’s for statements iterates over the items of any sequence (list, string, array…), in the order that they appear in the sequence.

For statement example

>>> beatles = ['john','paul','george','ringo']
>>> for beatle in beatles:
...     print(beatle)
... 
john
paul
george
ringo

This kind of loop is known in other programming languages as for each loop, where we discard the use of a controller and iterates the data structure directly.

3. While statement

Different from for statement that iterates over elements, the while statement is used to repeat an execution in the code as long as an expression is true.

While statement example

>>> beetlejuice = 0
>>> while beetlejuice < 3:
...     print('Beetlejuice!')
...     beetlejuice += 1
... 
Beetlejuice!
Beetlejuice!
Beetlejuice!

Important: be careful with your while statement due to the validation you want to do with it. If your condition is always true and never changes its state, you can fall into an Infinity loop triggering dozens of issues in your application.

While statement NEVER do this

>>> a = 1
>>> b = 0
>>> while a > b:
...     print('INFINITY LOOP!')
INFINITY LOOP!
INFINITY LOOP!
INFINITY LOOP!
INFINITY LOOP!
INFINITY LOOP!
INFINITY LOOP!
INFINITY LOOP!
INFINITY LOOP!
INFINITY LOOP!
INFINITY LOOP!
INFINITY LOOP!

There are other statements that help to avoid this scenario that we’ll see later in this article.

4. Match statement

Starting on Python’s 3.10 version, a match statement validates an expression, comparing its value with successive patterns given as one or more case blocks. This statement is pretty similar to switch case from other languages like C, Java, and Javascript.

Match statement example

def http_error(status):
    match status:
        case 400:
            return "Bad request"
        case 404:
            return "Not found"
        case 418:
            return "I'm a teapot"
        case _:
            return "Something's wrong with the internet"

The last case (_) is the default pattern which means none of the previous cases match. In that case, the match statement uses the _ value as a scape in the loop, returning its result.

Also, we can use the clause | (or) when several cases can return the same answer.

Match statement with OR clause

case 401 | 403 | 404:
    return "Not allowed"

5. Range function

The range() function is not a loop properly but can be used to iterate a sequence of numbers.

Range function example

>>> for i in range(5):
...     print(i)
...
0
1
2
3
4

We can also determine to start in a specific number, specify a different increment, or even use a negative number in the range.

Range function start and end

>>> list(range(5, 10))
[5, 6, 7, 8, 9]

>>> list(range(0, 10, 3))
[0, 3, 6, 9]

>>> list(range(-10, -100, -30))
[-10, -40, -70]

6. The break, continue and else statements

The next statements were created to improve the loop’s execution and are commonly used in Python’s environment.

6.1 break

The break statement is used to stop the execution of a for or while loop.

break statement example

    i = 1
    while i < 6:
        print(i)
        if i == 3:
            print('Limit reached.')
            break
        i += 1
$ python3 -m reach_limit    
1
2
3
Limit reached.

6.2 continue

Different from break statement, the continue statement keeps the loop until the next iterating.

continue statement example

def find_odds_and_evens(start, end):
    for num in range(start, end):
        if num % 2 == 0:
            print("Found an even number", num)
            continue
        print("Found an odd number", num)
$ python3 -m find_odds_and_evens   
Found an even number 2
Found an odd number 3
Found an even number 4
Found an odd number 5
Found an even number 6
Found an odd number 7
Found an even number 8
Found an odd number 9

6.3 else

We can use else as a statement on a loop to run a block of code once when the condition no longer is true.

else statement example

def loop_with_else():
    i = 1
    while i < 6:
        print(i)
        i += 1
    else:
        print("i is no longer less than 6")
python3 -m loop_with_else     
1
2
3
4
5
i is no longer less than 6

7. Summary

And that’s it! We saw how to create loops in Python. Also, we could see the different kinds of loops that exist in Python’s environment and did some examples.

Furthermore, we learned the break, continue, and else statements used to help to control the loop, improving the control flow of our code.

This article was based on Python’s official documentation and more details can be found here.

8. Download the source code

Download
You can download the full source code of this example here: Loops in Python

Sergio Lauriano Junior

Sergio is graduated in Software Development in the University City of São Paulo (UNICID). During his career, he get involved in a large number of projects such as telecommunications, billing, data processing, health and financial services. Currently, he works in financial area using mainly Java and IBM technologies.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments
Back to top button