FOR Loop in Python

The for statement in Python allows me to create a determinate loop with N iterations.

for item:
instruction block

The for loop iterates over the contents of an object (list, tuple, string, etc.)

For each n-th element in the object, it executes the indented block of instructions within the for structure.

Note: The instruction block is not enclosed in braces. Python uses significant indentation. Therefore, it is sufficient to indent the block within the for loop.

A Practical Example

To create a loop with 5 iterations without using any object, I use the range function.

  1. for i in range(1,5):
  2. print(i)

The range() function creates an object containing 5 elements.

>>> list(range(1,5))
[1, 2, 3, 4, 5]

The for loop reads each element one by one and assigns it to the variable i.

The script output is as follows:

1
2
3
4
5

The loop runs for 5 iterations.

How to Stop Iterations

To stop the iterations of the for loop before it completes, you can use the break or continue statements.

  • Break: Stops the loop. The program jumps to the first instruction after the loop.
  • Continue: Skips the current iteration and proceeds to the next one.

The Difference Between Break and Continue: These statements serve different purposes. The break statement exits the loop entirely, while the continue statement skips only the current iteration and continues with the next one.

Example 1 (break)

  1. for i in range(1,5):
  2. if i==3: break
  3. print(i)

The output is:

1
2

The loop terminates on the third iteration.

Example 2 (continue)

  1. for i in range(1,5):
  2. if i==3: continue
  3. print(i)

The output is:

1
2
4
5

The third iteration is skipped, but the loop continues with the next one.

Other Practical Examples

Example 1

In this script, I define a list object "seasons" containing the names of the seasons of the year.

  1. seasons=["winter", "spring", "summer", "autumn"]
  2. for n in seasons:
  3. print(n)

The for loop reads each element of the list and assigns it to the variable n.

Then the print statement outputs the value of the variable n.

The program output is:

winter
spring
summer
autumn

Example 2

This script is similar to the previous one, but I use the enumerate() function to keep track of the loop count.

  1. seasons=["winter", "spring", "summer", "autumn"]
  2. for n, v in enumerate(seasons):
  3. print(n, v)

The for loop assigns the numerical counter (enumerate) and the value of each list element to the variables n and v.

Then it prints them.

The output is:

0 winter
1 spring
2 summer
3 autumn

Example 3

This for loop iterates over the characters in the string "Rome" and prints them on the screen.

  1. city="Rome"
  2. for n in city:
  3. print(n)

The script output is:

R
o
m
e

Example 4

To create a loop that decrements from 5 to 1, I use the range() function with a negative step.

  1. for i in range(5,0,-1):
  2. print(i)

In this case, the list consists of [5, 4, 3, 2, 1]. Same numbers but in reverse order.

The script output is:

5
4
3
2
1

The loop runs for 5 iterations in reverse order.

Example 5

In this example, I create a loop with a step of two.

  1. for i in range(1,10,2):
  2. print(i)

The output is:

1
3
5
7
9

Example 6

In this example, I create a dictionary variable and read it with the for statement.

  1. dictionary=dict()
  2. dictionary['it']='italian'
  3. dictionary['en']='english'
  4. for n,z in dictionary.items():
  5. print(n,z)

The items() method returns a sequence of tuples (key, value) from the dictionary.

In each iteration, the for loop assigns the key and value to the variables n and z. Then it prints them.

The output is:

it italian
en english

Example 7

In this example, I use the zip() function to pair two different lists.

  1. seasons_it=["winter", "spring", "summer", "autumn"]
  2. seasons_en=["winter", "spring", "summer", "autumn"]
  3. for n,z in zip(seasons_it, seasons_en):
  4. print(n,z)

The zip() function pairs elements from the lists that have the same index.

In each iteration, the for loop assigns the paired elements to the variables n and z. Then it prints them.

The output is:

winter winter
spring spring
summer summer
autumn autumn

 
 

Please feel free to point out any errors or typos, or share suggestions to improve these notes. English isn't my first language, so if you notice any mistakes, let me know, and I'll be sure to fix them.

FacebookTwitterLinkedinLinkedin
knowledge base

Loop Structures in Python

Forced Interruptions and clauses