Skip to content

For Loop

In programing, loops allow you to execute instructions repetitively. The while loop will repeat the instructions while a certain condition is true. The for loop will repeat the instructions for a specific number of times.

A for loop is used for iterating over a sequence and executing the same set of instructions for each item of the sequence.

The syntax of the for is the following:

🐍 Python Script
for iterator in sequence:
    instructions

where the iterator is a variable existing only inside the for loop, the sequence is a string, a list, a tuple, a dictionary or a set (we will see those later on) and the instructions are indented.

Info

Try to pick a meaningful name for the iterator variable such as letter if you go through a word or name if you go through a list of names.

Examples

🐍 Python Script
for letter in "banana":
    print(letter)
📋 Output
>>> %Run example1.py
b
a
n
a
n
a
>>>  

This code goes through a word, using the for loop, and prints each letter of the word.

🐍 Python Script
for name in ["Antoine", "Julie", "Quentin", "Alice"]:
    print("hello")
📋 Output
>>> %Run example2.py
hello
hello
hello
hello
>>> 

This code goes through a list of name and prints each time the word hello.

🐍 Python Script
count = 0
for name in ["Antoine", "Julie", "Quentin", "Alice"]:
    count += 1
print (count)
📋 Output
>>> %Run example3.py
4
>>>

This code initialise a variable count to 0. It then goes through the list of names and for each name, it adds 1 to the variable count. Then it prints the value of the variable count.

Range Function

If you want to loop a specified number of times, you can use the range() function as a sequence.

The range() function returns a sequence of numbers. By default, it starts from 0, increases by 1 and ends at the specified number minus 1.

Examples

📋 Interpreter
>>> for x in range(5):
    print (x)

0
1
2
3
4
>>> 

range(5) creates a sequence from 0 to 5 not included and increasing by 1 each time.

📋 Interpreter
>>> for x in range(4, 8):
    print (x)

4
5
6
7
>>>

range(4, 8) creates a sequence from 4 to 8 not included and increasing by 1 each time.

📋 Interpreter
>>> for x in range (5, 15, 3):
    print(x)

5
8
11
14
>>> 

range(5, 15, 3) creates a sequence from 5 to 15 not included and increasing by 3 each time.

📋 Interpreter
>>> for x in range (10, 6, -1):
    print(x)

10
9
8
7
>>> 

range(10, 6, -1) creates a sequence from 10 to 6 not included and decreasing by 1 each time (increasing by -1).

🐍 Python Script
total = 0
for val in range(6):
    total += val
print(total)

This code will add all the numbers between 0 and 5 and then print the result (15).

📋 Interpreter
>>> for number in range(8):
    print("#" * (number + 1))

#
##
###
####
#####
######
#######
########
>>> 

This code prints a pyramid of #, starting with 1 and ending with 8.