In this lesson we will study the for loop in Python and introduce the range() function.
In the last lesson we studied the while loop, which allows you to repeat one or more statements based on the truth value of the specified condition. Unlike the while, the for loop iterates based on a fixed number of times, that is, a defined number of times.
Python for loop syntax and the range variable
The syntax of the for loop is, therefore, the following:
for variable in range(): instructions
- for and in are the keywords.
- variable is the name of the variable that you will choose according to the rules explained in the previous lessons.
- range() is a function that can take as arguments:
- an integer indicating how many times the repetition is performed. For example if we put 3 the repetition is repeated three times from 0 to 2.
- two numbers indicating the start and end value (excluded) that the counter assumes.
- three numbers where the first two indicate the start and end value of the counter while the third indicates the increase that the counter assumes at each repetition.
Let’s do some practical examples right away in order to better understand how this cycle works.
First example of a for loop in Python
for i in range(3): print(i)
This script outputs the values 0, 1 and 2.
Therefore, initially i is zero and then, at the end of the cycle, it will reach the value 2.
Second example of a for loop in Python
for i in range(1,3): print(i)
In this specific case, the index starts from 1 and ends at 2. So this script produces the values 1 and 2 as output.
Third example of a for loop in Python
for i in range(1,9,2): #2 è lo step – indica il passo di avanzamento print(i)
In this case the index starts from 1 and changes in steps of 2 up to 9 excluded. Thus, the output will be: 1, 3, 5, 7.
Of course, it can also be displayed in descending order, such as:
for i in range(9,1,-2): print(i)
It will display the numbers: 9, 7, 5, 3.
Fourth example of a for loop in Python
The range() function can be customized as you like and you can get numbers in descending order, for example.
for i in range(10,0,-1): print(i)
The output produced is as follows: 10, 9, 8, 7, 6, 5, 4, 3, 2, 1
In the print function, you can also add the keyword end to prevent the carriage return in the output.
for i in range(10,0,-1): print(i, end=' ')
In this case there is an empty space between one number and another.
You can also insert a separator character such as a comma or hyphen: print (i, end = ‘-‘).
In this lesson we have explained the functionality of the for loop in python, in the next lessons I will propose many exercises in which this loop will be applied.