Python loops

by Alex
Python loops

A very important part of structured programming, besides condition statements, are loops. They help automate sequential tasks in a program, namely, to repeat the execution of certain code sections. This is quite often needed when it is necessary to do something many times, thus, loops simplify the task.

The concept of loops

We often encounter cyclic tasks in our life. We can refer to them any kind of lists, be it groceries, tasks for the day or scheduled exams. Indeed, when we go to the store, we buy everything on our list without stopping until we do it. In programming, loops allow an action to be repeated depending on the fulfillment of a given condition. This is how an execution of a repetitive sequence of instructions is organized. There are some other important concepts to know:

  • The body of a loop is the sequence of code that needs to be executed several times.
  • A single execution is an iteration.

Python also allows you to create nested loops. So, first the program will start an outer loop and in its first iteration it will go into a nested one. Then it will go back to the beginning of the outer loop and call the inner loop again. This will happen until the sequence completes or is interrupted. Such loops are useful if you need to go through a certain number of items in a list. There are only two loops in Python: for and while. The former is mostly used when you want to write a multi-level program with many conditions.

The for loop

The for loop in Python 3 executes the written code repeatedly according to the variable or counter entered. It is only used when you want to loop through the elements a known number of times. What does this mean? We have a list, and we take the first item from it, then the second item, and so on, but we do the action in the for body with each item. Roughly it looks like this:

for [item] in [sequence]:
    [do specified]

For can contain data of different types: numbers, words, etc. Let’s look at an example:

for i in 10, 14, 'first', 'second':
    print(i)

After you execute this, the following entry will appear on the screen:

10
14
first
second

Therange() function, or range, is often used to simplify things. In loops, it specifies the number of times the sequence should be repeated, specifying which items from the for list we need at the moment. It can specify from one to three numbers in parentheses:

  • one indicates that we should check all numbers from 0 and up to it;
  • two says to go through all the numbers in between;
  • three numbers will generate a list from one to two, but in increments equal to the third digit.

Consider an example. Theoretically, you could write it like this:

for i in [14, 15, 16, 17, 18]:
    print(i)

But this is too costly, especially if there are too many numbers, so it’s better to do it this way using the range() mentioned above:

for i in range(14,18):
    print(i)

In both the first and second cases, you will see the following sequence

14
15
16
17

The “while” loop

While is an English word that means “as long as”. This is a fairly universal loop, it’s a bit like the if condition, but its code is not executed once. Its condition is written before the body of the loop. After it is executed the first time, the program goes back to the header and repeats all the steps again. This process ends when the loop condition can no longer be met; in other words, it is no longer true. It differs from the previous for loop in that the number of checks is not known beforehand. Incidentally, it is also called a preconditioned loop. The Python recording of the while loop looks like this:

while [condition is true]:
    [do specified]

Here is an example of how to use this loop:

count = 0
while count < 6:
    print(count)
    count += 2

This loop gives the variable a value of 0 and then starts a loop to check if the number should be less than 6. The body of the loop also contains two instructions: the first prints the number itself and the second increments the number by two. The loop thus runs as long as the condition continues to be true. The following sequence of numbers will appear on the screen in front of you:

0
2
4
After the loop body, you can specify else and a block of operations to be performed when while is over.

Usually it only makes sense if a break instruction is specified, but the program works without the latter. Let’s look at the code:

count = 3
while count < 7:
    print count, " less than 7"
    count = count + 1
else:
    print count, " not less than 7"

The variable is 3, we specify the condition that while it is less than 7, we have to print it and the expression “less than 7”, then we have to add 1 to it. If it already becomes 7, then the else clause will be executed and the display will show that the variable is at least 7. The result of running this code is that we will see:

3 is less than 7
4 is less than 7
5 is less than 7
6 is less than 7
7 is not less than 7

Break and continue instructions

The break statement is used to exit a Python loop – it terminates the loop prematurely. So, if during code execution the program encounters a break, it immediately stops the loop and exits it, bypassing else. This is necessary, for example, if an error is detected while executing instructions and further work is pointless. Let’s look at an example of its use:

while True:
name = input('Enter name:')
    if name == 'enough':
        break
print('Hi', name)

His implementation will look like this:

Enter name: Irina
Hi Irina
Type name: Alexey
Hi Alexey
Enter name: Enough

After that the program will be aborted. Another instruction that can change the loop is continue. If it is specified inside the code, all remaining instructions until the end of the loop are skipped and the next iteration begins. In general, you should not get too carried away using these instructions.

Postconditioned loops

Many other programming languages have loops with a postcondition, usually described as follows:

  • repeat [here executable code] until [continuation conditions];
  • do [execute code here] while [continuation conditions];
Unfortunately, Python does not have a loop with a postcondition!

A while loop can become a loop with a postcondition, then its approximate form would be as follows:

while True:
    if not condition:
        break

Or like this:

while condition is True:
    stuff()
else:
    stuff()

So the loop’s body is given first, and then the condition is given.

Endless loops

Infinite loops in programming are those in which the exit condition is not satisfied. A while loop becomes infinite when its condition cannot be false. For example, you can use it to implement a program called “Clock”, which shows the time infinitely. An example of a Python implementation of an infinite loop would be this code:

Num = 3
while num < 5:
    print "Hello."

Obviously, a given variable will always remain the number 3, since there is no set increment, so the word “Hello” will just appear on the screen. Often the loop should not be infinite, because this causes the program to be unstable. In order to exit it, you need to press the key combination: CTRL+C. However, programs from which there is no exit also exist. These are: operating systems, microcontroller firmware.

Nested loops

Let’s look at nested loops in Python. Both nested for and while can be used for implementation. We have already written about them above. Here we would like to give you some examples of their use. They are very often used in two-dimensional lists. Here is an example of creating a two-dimensional list and displaying it with print.

d = [[1,2,3],[4,5,6]]
for i in range(2) 
    for j in range(3) 
        print(d[i][j])

You cannot use a single break in Python to get out of two loops at once. In this case you need to create a condition in the outer loop as follows.

toExit = False
while True:
    while True:
        toExit = doSomething()
        if toExit:
            break
    if toExit:
        break

Here is an example of using a loop in Python. Both are infinite. Everything will execute infinitely, until the doSomething function returns True. After that, break in the outer loop and break in the inner loop will be triggered alternately.

Conclusion

As a rule, commands in code are executed sequentially: one after another. This is why loops are used when you need to execute the body of the code more than once. Loops are very important in Python because they are what make repetition simple, logical and very clear.

Related Posts

LEAVE A COMMENT