Prodotti da non perdere

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
        count_o += 1

print('The even numbers entered are: ', count_e, '\nThe odd numbers entered are: ', count_o)

Try the code in the online compiler at the following link: Python compiler online

Exercises for Python – Exercise 2

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.

Some useful links

Python tutorial

Python Compiler

Install Python


Assignment operators



How to find the maximum of N numbers

How to use the math module

Bubble sort

Matplotlib Plot