Loops
While loops
In English, while means "as long as". We will therefore execute the instructions contained in the while
block as long as a defined condition is verified.
Let's make a simple example: a countdown.
start_val = 3
while start_val >= 0:
print(start_val)
start_val -= 1
3
2
1
0
The structure of a while
block is very similar to that of an if
block:
- the keyword is followed by a boolean
- we find the
:
character at the end of the line - the block of instructions to execute is indented by one level
For loops
In English, for means "for". The typical use of a for
loop will be for example for a sequence of numbers.
Thus, we can for example perform instructions "for each item of the sequence 1, 2, 3, 4, 5."
Let's make a simple example: multiplication tables.
number = 7
for i in [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]:
print(i*number)
7
14
21
28
35
42
49
56
63
70
Traversing a sequence
We briefly saw the for
keyword, particularly its use in combination with the range()
function. Thus, we were able to perform iterations on a defined number of elements.
The for instruction also allows traversing sequences: typically, tuples or lists! The structure is identical to using range()
, and here's an example:
# creating a list, this works the same way with a tuple
prime_numbers = [1, 3, 5, 7, 11, 13, 17]
for nb in prime_numbers:
print(nb, "is a prime number.")
1 is a prime number.
3 is a prime number.
5 is a prime number.
7 is a prime number.
11 is a prime number.
13 is a prime number.
17 is a prime number.
It is important to note that for a for
loop, there is no longer a condition to be met for the loop to occur.
range()
function The
The range()
function is a predefined function in Python. It allows generating sequences automatically. Thus, it is very practical for creating for
loops.
It can take one, two or three arguments depending on the sequence we want to create.
range(start, end, step)
Parameter | Type | Description |
---|---|---|
start | int | Indicates what value the sequence starts with. By default, it equals 0 . |
end | int | Corresponds to the excluding limit: if end equals 10 , the sequence will end at 9 . |
step | int | Represents the increment: by default, step equals 1 , because the sequence advances by 1. |
# We define a printRange function
# printRange displays on a single line a sequence generated by range()
def printRange(range):
for i in range:
print(i, end=" ")
print()
printRange(range(10))
printRange(range(3, 10))
printRange(range(1, 10, 2))
printRange(range(0, 100, 10))
0 1 2 3 4 5 6 7 8 9
3 4 5 6 7 8 9
1 3 5 7 9
0 10 20 30 40 50 60 70 80 90