Hey there! Welcome to Hostman! 🎉

Loops in Python 3

06.12.2023
Reading time: 8 min
Hostman Team
Technical writer

You're probably already familiar with the if statement and the if-else and if-elif-else constructs. Now let's learn about loops. In this article, we will look at the simplest for and while loops, statements for interrupting and continuing them (break and continue, respectively), and examples of using if-elif-else statements to create additional conditions.

Loops in Python 3 and why you need them

Cyclic tasks are an integral part of our lives. Take shopping for groceries with a list. We look at the list, look for the desired product and put it in the cart, then go to the second item and repeat the same operation until the end of the list, after which we exit the program discard the list and move on to the next part of the code task. After the last item is executed, the list is discarded. Loops work in programming in the same way: the program will continue executing a certain piece of code as long as some condition specified for this piece or, as programmers say, for the loop body, is met.

The conditions are set with the special operators while or for, and a single execution of the loop body is called an iteration. There can be as many iterations as you want and they will be executed as long as the condition is true. If you make a logical mistake when writing the code, the iterations risk becoming infinite. In such cases, we speak of infinite loops, which, however, can be called intentionally.

For Loop in Python

The for statement is needed to loop through a known number of values in a list. for is one of the main helpers of a Python programmer; it saves a lot of time since you don't have to retype the same code many times. But enough theory, let's write some code to make it clearer what for does:

word = "hostman"
for letter in word:
   print (letter)

We get this result:

h
o
s
t
m
a
n

The program searches through all elements, in this case the characters that make up the string, and outputs them as a sequence. But they can also be elements of a list. A list is created using [] symbols, and its elements are enumerated using commas. For example, let's take our shopping list and display it on the screen:

products = ['milk', 'bread', 'eggs', 'sausage', 'sugar', 'flour']
for element in products:
   print (element)
milk
bread
eggs
sausage
sugar
flour

Now, a few remarks for beginners:

  • Do not forget the indentation in the loop body after the main lines with for and while operators.

  • You can use single or double quotes to correctly label strings and elements (in the examples above, we used both types), but in practice, it's better to use one of them so as not to worsen the code readability.

  • Programmers usually use variables i and j to denote counters, but it's possible to label them differently. In these examples, for the sake of clarity, we have intentionally labeled counters as letter and element to make it clear which values they search for.

While Loop in Python

The function of the while statement is different. As long as the condition entered by while is true, the loop body will continue to execute, and the number of iterations is not known in advance (unlike loops with the for statement). Example:

number = 1
while number < 10:
    print (number)
    number += 2
print ('The next value is greater than 10, so the count stopped.')

Here is the result of executing the code:

1
3
5
7
9
The next value is greater than 10, so the count stopped.

One of the features of Python is that the language is as visual as possible, and it's often clear what work the code is doing without detailed explanations. In this case, we have the following: we assigned the value 1 to the number variable and created a condition—as long as the value is less than 10, the loop body will be executed. In the body, we have created two instructions, one visible (to display the next value on the screen) and the other one adds the specified number to the variable value and overwrites this value. We could rewrite this line as follows:

number = number + 2

The entries x = x + 2 and x += 2 are equivalent (Python allows you to use different code to do the same thing in some cases).

As soon as the condition introduced by the while statement is no longer true (the number becomes greater than 10), the loop body stops executing, and the program moves to the final line (note that it is on a different level, so it is not indented), and a message is displayed:

The next value is greater than 10, so the count stopped

Using if-elif-else statements on loops

Now let's consider more complex and functional examples of constructs with while, which are created using the if, elif, and else statements. 

x = 0
while x < 10:
    if x == 0:
        print (x, "if statement is true")
        x += 1
    elif x <= 5:
        print (x, "First elif statement is true")
        x += 1
    elif x > 5 and x < 9:
        print (x, "Second elif statement is true")
        x += 1
    else:
        print (x, "else statement is true")
        x += 1
print ("That’s the count.")

Here’s the result:

0 if statement is true
1 first elif statement is true

6 second elif statement is true

9 else statement is true
That’s the count.

After assigning the value 0 to the variable x, we create a condition for the while loop, and using the if, elif and else operators, we add a set of conditions that will cause a certain text to be displayed on the screen. The if condition triggers when x is 0, and the first elif triggers when x is less than or equal to 5. In the case of the second elif, we also used the and operator, which adds an extra condition so that the user also sees the text that is displayed when the else condition is met. Python checks the truth of conditions sequentially, so if any condition higher up on the list remains true until the last iteration, the directives for the conditions below will not be executed.

Break and Continue Statements

The break and continue statements provide additional ways to work with loops. Here's what they do:

  • break is used to interrupt a loop;

  • continue is used to skip a certain iteration and move on to the next one, but without terminating the loop.

For an example of how the break statement works, let's slightly modify the code from the previous chapter and try to execute it:

x = 0
while x < 10:
    if x == 0:
        print (x, "if statement is true")
        x += 1
    elif x <= 5:
        print (x, "first elif statement is true")
        x += 1
    elif x > 5 and x < 9:
        print (x, "second elif statement is true")
        x += 1
    else:
        print (x, "else statement is true")
print ("That’s the count.")

We removed the x += 1 line after the else operator and got into an infinite loop! Of course, we can just return the line, but we can also do it this way:

x = 0
while x < 10:

    else:
        print (x, "else statement is true")
        break
print ("That’s the count.")

Now, after adding the break statement, when the else condition is met, the loop will no longer be infinite, and the message will appear on the screen (That's the count).

Here is an example of how the continue statement works:

products = ['milk', 'bread', 'eggs', 'sausage', 'sugar', 'flour']
print ('Shopping list:')
print ()
for element in products:
    if element == 'sausage':
        continue
    print (element)
print ()
print ('And sausage is already bought.')

The result of the program:

Shopping list:
milk
bread
eggs
sugar
flour
And sausage is already bought.

As we can see, the sausage is no longer on the list: as soon as the program reaches it, the continue command comes into play, instructing it to ignore this item. But the loop is not interrupted, so the other products from the list are also displayed on the screen.

Nested Loops in Python

You can also use loop operators to create nested loops in Python 3. 

Example:

for i in range (1, 4):
    for j in range (1, 4):
        print (i * j, end=" ")
  print ()

The result of the program:

1 2 3
2 4 6
3 6 9

You have already guessed that this is the way to achieve consecutive multiplication of numbers (the i * j directive inside nested for loop is responsible for this, and the code end="" prints the obtained values with spaces). The last print() line, referring to the main for loop (this is implemented by indentation), is also necessary for clarity: in this case the program will print the obtained values in a column.

Beginners may also ask why there is no 4 8 12 line in the output? This is a peculiarity of the built-in range function that specifies the range of values: it does not include the last number, so for that line to appear, we should write the code like this:

for i in range (1, 5):
    for j in range (1, 4):
        print (i * j, end=" ")
  print ()
1 2 3 
2 4 6 
3 6 9
4 8 12 

Conclusion

In this short article, we got acquainted with for and while loops, learned how to use conditional if-elif-else constructs together with loops, and how to use break and continue statements. With a little practice, you will be able to write more complex code than presented in our examples. Good luck!