Up until now, the control flow of your programs was only from top to bottom. However, when writing more complex programs, it is often necessary to execute a specific piece of code several times in a row, and this is where loops come into play.
Python While Loops
Python (and many other programming languages) offers two different loops. The first one is the while
loop. A while loop repeatedly executes a code section as long as a given condition evaluates to True
. One code execution within a loop is called an iteration. In the following flow chart, 1
is added to x
as long as x < 10
afterward x
will is printed and the program terminates.
In Python code, this program looks as follows:
1
2
3
4
5
6
7
if __name__ == "__main__":
x = 0
while x < 10:
x += 1
print(x)
From this little example, you can see how a while
loop is structured in Python. Similarly to if
and elif
(Python Course #7) first comes the while
keyword followed by the condition which ends with a colon :
. Indented under the while
statement is the code that is executed when the condition evaluates to True
:
1
2
while CONDITION:
CODE TO EXECODE AS LONG AS CONDITION IS TRUE
The condition of a while
loop can be as complex as you like including all comparison and boolean operators you know by now. But a bad condition can lead to the loop running indefinitely, a so-called infinite loop, or the code not running at all. There are also no restrictions for the code within a while loop (the code indented under the while
statement); every valid Python code is also valid inside a loop. You can even have loops inside a loop.
Python While Loop Else
A while
loop can have an else
block in Python. The code indented under the else
statement is executed if the condition of the while
loop is False:
1
2
3
4
5
6
7
8
if __name__ == "__main__":
x = 12
while x < 10:
x += 1
print("x is greater than 10, add 1")
else:
print("x is not less than 10")
The code example above produces the following output:
1
2
3
x is greater than 10, add 1
x is greater than 10, add 1
x is not less than 10
Python Loops Break and Continue
During an iteration, the code inside a loop can skip the rest of the current iteration and tell the loop to start the next iteration or even stop the loop entirely. To skip the current iteration and start the next one, the keyword continue
is used:
1
2
3
4
5
6
7
8
9
if __name__ == "__main__":
x = 3
while x < 10:
print(x)
x += 1
if x > 7:
continue
x += 1
In the example above 1 is added two times to x
until x
is greater than 7. Afterward, 1 is only added once per iteration. Because the if
statement in line 7 calles continue
in every iteration after 8 was assigned to x
. The continue
statement is often helpful when optimizing the run time of code. When it is clear that a section of code does not change the data to affect the program after the loop, this code can be skipped, which saves run time.
To end the execution of a loop entirely, use the break
statement. Sometimes the condition of a while
loop can become very complex, and it might be easier to state when the iterations should stop. In such a situation, the condition of a while
loop is set to True
, and an if
statement is added that executes break when it’s condition evaluates to True
:
1
2
3
4
5
6
7
8
9
if __name__ == "__main__":
x = 3
while True:
x += 1
if x >= 10:
break
print(x)
You can also use multiple continues
and breaks
within a loop. But keep in mind that it can become quite challenging to find an error in such a program.
Python For Loops
The second type of Python loops are for
loops. In contrast to while
loops, for
loops don’t run until a condition evaluates to False
. They iterate over a data sequence such as a string, list
, set
, or tuple
.
1
2
3
4
5
if __name__ == "__main__":
s = "Hello!"
for c in s:
print(c)
In the for
loop above, a single character of the string s
is retrieved and assigned to c
. In each iteration, a new character is retrieved from s
and printed, producing the following output:
1
2
3
4
5
6
H
e
l
l
o
!
The variable(s) that is used and changed in every iteration is written in front of in
it is also called the iteration variable. The variable name of the data structure that provides the data for each iteration is stated after the in
named iterator:
1
2
for ITERATION_VAR in ITERATOR:
CODE TO EXECUTE IN EVERY ITERATION
When a for
loop iterates over an ordered data structure such as str
, list
, or tuple
the first iteration will access the element at index 0. After each iteration, the index is increased by 1. When an unordered data structure such as a set
is used, the order of elements that are retrieved for each iteration is arbitrary:
1
2
3
4
5
6
7
8
9
10
11
if __name__ == "__main__":
l = ['a', 'b', 'c']
s = {'a', 'b', 'c'}
print("list:")
for c in l:
print(c)
print("set:")
for c in s:
print(c)
(Possible) output of the code above:
1
2
3
4
5
6
7
8
list:
a
b
c
set:
c
a
b
Python For Loop Over Number Range
for
loops are handy when a piece of code has to be executed a specific amount of times. For example, if you want to run a piece of code precisely 10 times, use the range(...)
function to get a range to iterate over:
1
2
3
if __name__ == "__main__":
for i in range(0, 10):
print(i)
The range(start, stop[, step])
function returns a range of numbers going from start
to stop-1
. If you only enter a single number into range(...)
, it is interpreted as stop
and the range starts at 0. Optionally, you can also specify step
if you only need every 2nd, 3rd, etc. number. The following code iterates over every second number starting from 0 up to the length of the list
l
(which is 6), and in each iteration, 1 is added to the list
element corresponding to the index i
:
1
2
3
4
5
6
7
if __name__ == "__main__":
l = [1, 2, 3, 4, 5, 6]
for i in range(0, len(l), 2):
l[i] += 1
print(l)
This code produces the following output:
1
[2, 2, 4, 4, 6, 6]
Python Loop Over Dictionary
Python dictionaries are also an ordered data structure (at least since Python 3.6), and you can iterate over them. If no dictionary function is called when iterating over a dictionary the for
loop iterates over the keys. However, making that explicit is better and using the .keys()
function. With the .values()
function, it is possible to iterate over all dictionary values. And in Python it is even possible to have multiple iteration variables, and therefore, you can iterate over the keys and values of a dictionary simultaneously:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
if __name__ == "__main__":
d = {'a': 0, 'b': 1, 'c': 2, 'd': 3}
print("keys:")
for k in d.keys():
print(k)
print("values:")
for v in d.values():
print(v)
print("key-value pairs:")
for k, v in d.items():
print(k, "->", v)
The code above produces the following output:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
keys
a
b
c
d
values
0
1
2
3
key-value pairs
a -> 0
b -> 1
c -> 2
d -> 3
Python Nested Loops
As stated at the beginning of this article, loops can contain loops. A prominent example of nested for
loops is the iteration over two-dimensional data. You can represent 2D data in Python with nested lists
. The first index represents the y
dimension in the following example, and the second index represents the x
dimension. The outer for
loop iterates over the y
dimension while the inner for
loop iterates over the x
dimension:
1
2
3
4
5
6
7
8
9
if __name__ == "__main__":
l = [[0, 1, 2],
[3, 4, 5],
[6, 7, 8]]
for y in range(3):
for x in range(3):
print(l[y][x], end=" ")
print("")
Output of the code above:
1
2
3
0 1 2
3 4 5
6 7 8
The code indented under the inner for
loop is executed every iteration of the outer and the inner loop. While the print(...)
indented by only one tab/spaces is only executed in the outer loop iterations. One of the most common bugs in nested loops is that code is executed on the wrong loop level. So make sure to double-check your code if all statements are at the correct indentation level. Especially in complex code such as the convolution layer of a neural network, seven nested for
loops are not uncommon.
Loops are probably one of the most important aspects of programming and will bring most of your programs to life. Make sure to get the free Python Cheat Sheets in my Gumroad shop. If you have any questions about this article, feel free to join our Discord community to ask them over there.