Loops

For loops, we also talk about iterative structures

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

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
We talk about conditional iteration.

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)

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.")

It is important to note that for a for loop, there is no longer a condition to be met for the loop to occur.

The range() function

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)

ParameterTypeDescription
startintIndicates what value the sequence starts with. By default, it equals 0.
endintCorresponds to the excluding limit: if end equals 10, the sequence will end at 9.
stepintRepresents the increment: by default, step equals 1, because the sequence advances by 1.
You will find more explanations at this address.
# 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))