lettura simple

How to do a FOR loop in Python

In this lesson I'll explain how to make a FOR loop by a practical example.

What is a FOR loop? It is an instruction that repeats the same block of code for a predefined number of times. Each repetition is called the loop iteration.

Example

For example, this script prints the numbers 1 to 10.

To indicate the beginning and the end use the instruction range().

example

The for statement performs ten iterations.

In each iteration the variable i is incremented by +1 and printed on the screen.

Here is the program output.

1
2
3
4
5
6
7
8
9
10

You can also use the for statement to read iterable objects, such as a list, tuple, or dictionary.

Example

For example, type this script to read and print the contents of a list.

example

The for statement iterates the contents of the iterable object from the first to the last element.

In each iteration, the current element is assigned to the variable i.

Note. The variable i equals "Red" in the first iteration, "Green" in the second iteration, and finally "Black" in the third and final iteration.

Here is the program output.

Red
Green
Black

If you like this lesson from Nigiara, keep following us.




Report a mistake or post a question




FacebookTwitterLinkedinLinkedin