1. About The for loop statements
The for loop in Python is used for iterating over a sequence or collection of items. It allows you to perform a specific set of actions repeatedly for each item in the sequence. This loop is particularly useful when you know the number of iterations in advance or when you need to iterate through the elements of a container like a list, tuple, string, or dictionary.
Syntax
The general syntax of a for loop in Python is as follows:
1 2 |
for item in sequence: # Code block to be executed |
Here's a breakdown of the different parts of the for loop:
- item: This is a variable that represents the current item being processed in the loop. You can choose any valid variable name to represent the item.
- sequence: This is the sequence or collection of items that you want to iterate over. It can be a list, tuple, string, range, or any other iterable object.
When the for loop is executed, it iterates through each item in the sequence one by one. For each iteration, the code block inside the loop is executed. Once all the items in the sequence have been processed, the loop terminates, and the program continues with the next statement after the loop.
2. The For loop in Python ...
The for loop in Python, allows to execute repeated instructions.
Syntax:
1 2 |
for counter in range(start_counter, end_counter): instructions... |
Example. display the first 10 numbers
1 2 3 |
for i in range (1,11): print(i) #prints the first 10 numbers 1, 2, ..., 10 |
Note
Note that in the loop for i in range(1, n) the last one which is n is not included! This means that the loop stops at order n-1.
3. The repetitive structure While
The while structure is used to execute a set of statements as long as a condition is fulfilled and execution stops when the condition is no longer satisfied.
Syntax
1 2 |
while (condition): intructions ... |
Example. display of the first 10 integers with the while loop
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
i = 1 while(i <= 10): print (i) i = i + 1 """ output: 1 2 3 4 5 6 7 8 9 10 """ |
4. Stopping a loop with break instruction
Sometimes we need to stop a loop when a certain result is reached. To immediately stop a loop, you can use the break keyword.
Example let's have fun looking for the first number greater than 10 in a list:
Exemple (searching the first number greater than 10)
1 2 3 4 5 6 7 8 |
L = [ 3 , 7 , 11 , 23, 31 , 20 , 27] for x in L: # we test if x > 10 if x > 10: print("The first number greater than 10 is : ", x) # on quitte la boucle break # output: The first number greater than 10 is : 11 |
Younes Derfoufi
CRMEF OUJDA