Today we’ll be talking about the basics of for loops.
Here’s the video version of this article:
We use loops if some code must be repeated multiple times. It can be either a fixed number of times or an indefinite number of times, until a condition is met. There are two types of loops: for loops and while loops. Let’s talk about for loops first.
We can use the for loop to iterate over the elements of a collection, so the for loop is a collection-controlled loop. The collection may be a sequence, a set, or a dictionary. We may also say it’s an iterator-based loop because it iterates over all the items in the collection.
The Syntax
The syntax is: After the for keyword we use a loop variable that will be set to each of the elements iterated over during the loop execution in turn and after that we use the name of the collection and finally there’s a colon. After the colon, in the next line, the block of code begins with instructions to be executed on each loop run. This repeated code is called the body of the loop.
Here’s a simple example with a list collection:
>>> names = ["John", "Kate", "Mike", "Alice", "Sarah"]
>>>
>>> for name in names:
... print(name)
...
John
Kate
Mike
Alice
Sarah
Here we only have one instruction in the code block. The loop takes each of the elements one by one, assigns its value to the loop variable name and then executes the code on it. In this case it just prints the value of name.
Here’s an example with a different collection, a string:
alphabet = "abcd"
print("Small letters:")
for letter in alphabet:
print(letter)
print("Capital letters:")
for letter in alphabet:
print(letter.upper())
Here we have some code that is executed only once because it’s not in a loop. It prints “Small letters” and “Capital letters”. We also have two loops. The first loop just takes the string alphabet letter by letter and prints all the elements. The second for loop does the same thing, additionally converting each letter to uppercase.
Here’s the output:
Small letters:
a
b
c
d
Capital letters:
A
B
C
D