The for loop statement in Python

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:

Here's a breakdown of the different parts of the for loop:

  1. 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.
  2. 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:

Example. display the first 10 numbers

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

Example. display of the first 10 integers with the while loop

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)

 

Younes Derfoufi
CRMEF OUJDA

Leave a Reply