Let’s do some exercises with the for loop in Python, in order to consolidate what we have studied so far.
For this purpose, let’s go back to an exercise in which we used the while, so as to be able to compare the two methods. The exercise can be viewed at this link: example while loop in Python.
Exercises for Python – Exercise 1
Input data 10 integers, count how many even and how many odd numbers have been entered.
First, I initialize the count_o and count_e variables to zero.
Then we simply use a for loop with the range (10).
As you can see, it is not necessary to initialize i to 0 as we did in the while, since the index i still starts from zero, unless otherwise specified in the range() function.
Within the cycle I enter the values and for each value entered I check if even or odd. I use the two variables previously initialized to zero to do this count.
Finally, with the for loop, I display the values of the two variables.
So here is the complete code of our simple program, which uses the for loop in Python:
count_o = count_e = 0
for i in range(10):
n = int(input('Insert a number: '))
if n % 2 == 0:
count_e += 1
else:
count_o += 1
print('The even numbers entered are: ', count_e, '\nThe odd numbers entered are: ', count_o)
Also this time we take up an exercise done with the while and we will carry it out with the for loop in Python, in order to be able to compare these two constructs again.
Take 15 integers as input and calculate the average.
First I initialize n to 15.
Simply because in this way, if for example I have to enter a number other than 15, just change the constant and no other data needs to be changed in the code.
Then with a for loop I ask for the numbers and store them in an average variable which I initialize to 0.
So I can solve the algorithm in this way using the for loop in Python:
average = 0
n = 15
for i in range(n):
a = int(input('Insert a number: '))
average += a;
average /= n
print('average is: ', average)
N.B. I use the mean variable for the sum and also for the mean, but I could also use two distinct variables if there was a need to display the sum as well.
In the next lesson I will propose some more exercises on the for loop in Python.
Dopo applichiamo la funzione len sull’elelemento list di Python:
len(stagioni)
Possiamo anche stampare il valore usando print:
print(len(stagioni))
Si avrà come risultato 4.
Possiamo anche utilizzare una variabile dove memorizzare il risultato:
len_stagioni = len(stagioni)
Quindi, in seguito, utilizzeremo la varibile len_stagioni all’interno del nostro programma, come ad esempio.
print(len(stagioni))
Len list Python – secondo esempio
Il calcolo della lunghezza di una lista è molto utile quando dobbiamo iterare.
Supponiamo ad esempio di voler stampare tutti gli elementi di una lista. Nel nostro caso di stagioni.
Dapprima presento un approccio errato al problema, spiegandovi le motivazioni.
stagioni = ['Primavera', 'Estate', 'Autunno', 'Inverno']
for i in range(4):
print(stagioni[i])
In questo caso il codice potrebbe anche andar bene, perchè non andrò mai ad aggiungere un’altra stagione alla lista. Ma pensate a delle liste che si possono facilmente espandere aggiungendo altri elementi.
Per far funzionare il tutto dovrò cambiare ogni volta il parametro all’interno di range! Ma vi sembra corretto? Direi proprio di no!
Allora come risolvo l’algoritmo? Utilizzando la funzione len sulla lista, in questo modo:
stagioni = ['Primavera', 'Estate', 'Autunno', 'Inverno']
for i in range(len(stagioni)):
print(stagioni[i])
Possiamo anche utilizzare la variabile dove memorizzare la lunghezza della lista.
stagioni = ['Primavera', 'Estate', 'Autunno', 'Inverno']
len_stagioni = len(stagioni)
for i in range(len_stagioni):
print(stagioni[i])
La funzione len, per il calcolo della lunghezza di una lista in Python, come vedremo più avanti, sarà molto utile quando vogliamo popolare gli elementi della lista senza produrre duplicati. Seguitemi nei prossimi tutorial per scoprire come fare!
It will print: [‘Spring’, ‘Summer’, ‘Autumn’, ‘Winter’]
Index of the list in Python
As we have already said, each element of the list is assigned an index that starts from the left and starts from 0. So, to print for example the first element we write:
print (seasons [0])
While to print the last element we write:
print (seasons [3])
As we have seen with strings, also with lists we can extract a set of values, that is a sublist:
print (seasons [: 2])
This output will only display the first two items in the list.
Editing list elements in Python
The elements of the list can also be modified by reassigning them a new value.
For example, we assign the value ‘Summer’ to the first element, while the value ‘Spring’ is assigned to the second.
seasons [0] = ‘Summer’
seasons [1] = ‘Spring’
In this simple example I have changed the first and second seasons.
Conclusion
In this lesson we introduced the concept of list in Python, in the next we will talk about the length of a list.
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
Where:
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
End keyword
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 = ‘-‘).
Conclusion
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.
Commenti recenti