Python language basics 19: for-loops
June 7, 2015 Leave a comment
Introduction
In the previous post we saw how we could iterate through a collection using the foreach-loop in Python. Foreach-loops are ideal when looping through collections and we looked at how lists and dictionaries can be iterated.
In this post we’ll look at the more traditional version of looping, called for-loops.
For-loops in Python
The loop control in for-loops is based on integers rather than items in a collection. We set an upper and a lower limit, say 0 and 3 and the body of the for-loop will be executed will be executed within those limits. The lower limit is inclusive whereas the upper limit is exclusive.
The function called “range” will be the tool to generate the upper and lower limit for the tool. Let’s see a basic example:
for x in range(0, 3): print(x)
This will print…
0
1
2
The variable ‘x’ can be called “mickeyMouse”, it doesn’t make any difference. In fact it’s customary to go with ‘i’, ‘x’ and ‘y’.
If you only pass in a single integer to the range function then that will be the upper limit and the lower limit will be set to 0:
for x in range(10): print(x)
0
1
2
3
4
5
6
7
8
9
We can also set a step variable which determines the increments for the loop:
for x in range(0, 11, 2): print(x)
…which prints…
0
2
4
6
8
10
If you want, you can use a for-loop to iterate through collections as well. This is a good alternative if you need to keep track of the element count and position. The “len” function gives us the number of elements in a collection which can be used as the upper limit in the for-loop. We then use the loop variable ‘i’ to access individual elements in the collection:
sizes = ["small", "medium", "large", "x-large"] collectionSize = len(sizes) for i in range(collectionSize): print(sizes[i])
…which prints…
small
medium
large
x-large
The for-loop can be extended with an else clause like we saw in the case of the if-else block. The else-block will be executed when the loop finishes:
for i in range(collectionSize): print(sizes[i]) else: print(i)
The else block will print ‘3’ as that is the final value of the variable i after the loop is done.
We’ll look at how a Python application can be started from the command line in the next post.
Read all Python-related posts on this blog here.