They exist in almost every programming language, but in Python, working with them is most enjoyable. As with everything else in Python.
Code in Python usually executes sequentially: the first line, then the second, the third, and so on. But some constructs allow you to break this order to perform more complex operations.
For example, loops execute the same block of code multiple times. In Python, there are two main types of loops: while
and for
. Let’s talk about them.
How Loops Work
Any loop consists of two essential elements:
- Condition: The initial parameter; the loop starts only if the condition is met and ends as soon as the condition is no longer met.
- Body: The actual code that runs inside the loop.
In Python syntax, a colon is placed at the end of the condition line, and the entire body is indented (with a tab or four spaces).
program before loop
condition:
first line of body
second line of body
program after loop
The while
Loop in Python
While
is the simplest and most understandable type of loop. It is also called a pre-condition loop.
x = 1
while x < 5:
print(x)
x += 1 # Equivalent to x = x + 1
>>> 1
>>> 2
>>> 3
>>> 4
Translated to plain language, the program means: “While x is less than five, print x and add one to it.”
However, the simplicity of while
hides a danger: it can easily become infinite. For example, if we remove x += 1
from the code above, it would look like this:
# This code will run indefinitely
x = 1
while x < 5:
print(x)
Here, nothing happens with the variable x
. It is always equal to one, so the loop condition never ceases to be true, and the loop never ends.
To avoid such situations, when using while
, you must ensure that the condition will eventually cease to be true. You can also use the break
statement, which we’ll discuss a bit later.
The for
Loop in Python
Programmers use the for
loop much more often than while
. Instead of a plain condition, we set a collection of data: a list, a tuple, a string, a dictionary, a range, or any other iterable object.
On each iteration, the program asks: “Are there any elements left in the object that I haven’t processed yet?”
Suppose we have a list of numbers: [14, 101, -7, 0]
. We can use it with for
to print each element separately.
num_list = [14, 101, -7, 0]
for number in num_list:
print(number)
>>> 14
>>> 101
>>> -7
>>> 0
Here, the variable number
is updated on each new loop iteration. First, it holds the first element, then the second, and so on until the list is exhausted.
We could name the variable number
anything we like. Often, letters i
, j
, and k
are used. If we never refer to this variable inside the loop, Python developers commonly use an underscore _
.
The range()
Function
When you need to apply for
to a numerical range, you can specify it with the range()
function. It can take from one to three arguments.
If there is one argument, it will form a range from zero to the number before the argument value.
for i in range(3):
print(i)
>>> 0
>>> 1
>>> 2
If there are two arguments, it will form a range from the first argument’s value to the number before the second argument’s value.
for i in range(23, 26):
print(i)
>>> 23
>>> 24
>>> 25
If there are three arguments, the first two work as before. The third indicates the step between numbers.
for i in range(10, 20, 3):
print(i)
>>> 10
>>> 13
>>> 16
>>> 19
Single-line Loop: List Comprehension
If only one action is performed in the for
loop body, Python syntax allows you to shorten it to a single line:
[i for i in iterable_object]
This syntactic sugar doesn’t add new functionality but improves the code’s appearance. It allows you to generate lists quickly and easily.
num_list = [i for i in range(1, 11)]
print(num_list)
>>> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
You can also add an additional condition to such a construct. Let’s make a generator that outputs only even numbers and directly prints the resulting list.
print([i for i in range(1, 11) if i % 2 == 0])
>>> [2, 4, 6, 8, 10]
The condition if i % 2 == 0
means: “if the remainder of dividing i
by 2 is 0.”
You can also perform operations on the variable i
. Let’s use the previous generator but output the squares of even numbers.
print([i ** 2 for i in range(1, 11) if i % 2 == 0])
>>> [4, 16, 36, 64, 100]
The main thing with this approach is not to get carried away. If the code becomes hard to read and understand (e.g., when multiple functions and methods are applied to i
and a complex condition is set), it’s better to split it into several lines. Clarity is more important than brevity.
Breaking a Loop: The break
Keyword
Sometimes you need to forcibly end a loop, even if its condition is still true. In such cases, use the break
keyword.
Let’s take the string “Hi, loop!” and print each of its characters. If we encounter a comma, we end the loop early.
string = 'Hi, loop!'
for i in string:
if i == ',':
break
print(i)
>>> H
>>> i
If the string doesn’t contain a comma, the loop will go through each of its characters and only then finish.
string = 'Hi loop!'
for i in string:
if i == ',':
break
print(i)
>>> H
>>> i
>>>
>>> l
>>> o
>>> o
>>> p
>>> !
Skipping Part of the Loop: The continue
Keyword
Sometimes you need to forcibly start the next loop iteration, skipping part of the body. For such cases, use the continue
keyword.
Let’s take the numbers from 1 to 10 inclusive and print only those that are not divisible by 2 or 3.
for i in range(1, 10):
if i % 2 == 0 or i % 3 == 0:
continue
print(i)
>>> 1
>>> 5
>>> 7
As you can see, if the if
condition is met (i.e., if the number is divisible by 2 or 3 without remainder), the remaining part of the body doesn’t execute, and i
is not printed.
Last Action in the Loop: The else
Keyword
Usually, the else
keyword is used in conjunction with if
, but it has another use. It can be used with while
or for
. In this case, the else
code executes after all iterations of the loop have completed.
If the loop is prematurely terminated by a break
, the else
part will not run.
Let’s revisit our code with the string “Hi, loop!” and add an else
block to it.
string = 'Hi, loop!'
for i in string:
if i == ',':
break
print(i)
else:
print('The loop ended without break')
>>> H
>>> i
Since there was a comma in the string, the break
triggered, and the else
block didn’t run. Now, let’s remove the comma and see what happens.
string = 'Hi loop!'
for i in string:
if i == ',':
break
print(i)
else:
print('The loop ended without break')
>>> H
>>> i
>>>
>>> l
>>> o
>>> o
>>> p
>>> !
>>> The loop ended without break
The loop went through all its iterations and finished on its own, so the else
code executed. It will also work if the loop doesn’t iterate at all.
while 1 == 0:
print('This line will never run')
else:
print('The loop ended without break')
>>> The loop ended without break
Infinite Loop
Sometimes, using an infinite loop can be a good idea. For example, if we are writing a game: it
should run as long as the player is playing. In this case, you need to use break
for exiting the loop.
To create an infinite loop, its condition must always be true. This can be done in several ways.
# Method #1 — "while true"
while True:
pass # pass is a placeholder statement that does nothing
If you use while False
, the loop will never start.
# Method #2 — "while any nonzero number"
while 1:
pass
while -4:
pass
while 2023:
pass
If you use while 0
, the loop will never start.
# Method #3 — "while non-empty element"
while 'string':
pass
while [False, 'list', 0]:
pass
If you use an empty element after while
(e.g., str()
or list()
), the loop will never start.
# Method #4 — Correct equation
while 1 == 1:
pass
while 0 != 1:
pass
An alternative approach is to place a variable with an appropriate condition after while
. For example:
# Method #1
condition = True
while condition:
pass
# Method #2
condition = 1
while condition:
pass
# Method #3
condition = 'string'
while condition:
pass
In such cases, you can exit the loop by changing the variable’s value to False
, 0
, None
, or any empty element. The loop will complete its last iteration and exit because the condition will no longer be met.
This approach is used when you need to exit the loop from other parts of the program: for example, from a function or nested loop. Another difference is that since the loop exits “naturally” without a break
, any else
code will execute (if present).
condition = True
x = 0
while condition:
print(x)
x += 1
if x == 3:
condition = False
else:
print('The loop ended without break')
>>> 0
>>> 1
>>> 2
>>> The loop ended without break
How to Create a do while
Equivalent in Python
In some programming languages, there is another type of loop — a post-condition loop. It always executes at least one iteration and only then checks if the condition is met.
In Java and C++, this is achieved with the do while
construct, but it doesn’t exist in Python. However, you can create an equivalent using an infinite loop and specifying the exit condition inside the loop body.
x = 12
while True:
x += 1
print(x)
if x > 5:
break
>>> 13
Whatever the value of x
, such a loop will go through at least one iteration. And that is a post-condition.
Nested Loops in Python
You can nest loops within each other in Python — that is, call one loop inside the body of another. This complicates the program’s logic.
You can nest any number of loops. Each new level of nesting requires increased indentation. It looks like this:
while condition:
pass
while inner_condition:
pass
pass
Let’s write a program that prints the iteration number of both the outer and inner loops.
for i in range(3):
print(f'Outer loop iteration: {i}')
for j in range(2):
print(f'Inner loop iteration: {j}')
>>> Outer loop iteration: 0
>>> Inner loop iteration: 0
>>> Inner loop iteration: 1
>>> Outer loop iteration: 1
>>> Inner loop iteration: 0
>>> Inner loop iteration: 1
>>> Outer loop iteration: 2
>>> Inner loop iteration: 0
>>> Inner loop iteration: 1
Summary
Loops are one of the main tools for any Python developer. With their help, you can perform many repetitive actions in just a few lines of code.
- Loops consist of a condition and a body. The code in the body executes only as long as the condition is met.
- Python has two types of loops:
while
andfor
. Inwhile
, the condition is set explicitly. Infor
, each element of a collection is iterated. - Different operators can be applied to both types:
break
to terminate,continue
to skip part of the body,else
to perform the last action before exiting the loop. - Loops can be made infinite (so the program never ends or only ends when a specific condition is met) and nested within each other.