I propose other exercises with the while in Python before moving on to other arguments.

While exercises Python – First exercise

Take 15 numbers as input and calculate the average.

First of all we give N the value 15. N therefore represents the quantity of numbers to insert. We use a counter variable that starts from 0 and increases each time by one until it reaches N. Then inside the while we ask you to enter a number and add it each time to the variable sum. After the cycle we calculate the average and display it.

So here is the complete Python code:

i, N = 0,15
sum = 0
while i < N:
    n = int(input('Insert a number:'))
    sum += n
    i += 1
average = float(sum / N)
print ('The average is:', average)

We could also use a single variable for both the sum and the average, since the sum variable is no longer used within the program.

Here is a possible variation to the solution proposed above:

i, N = 0, 15
average = 0
while i < N:
    n = int(input('Insert a number:'))
    average += n
    i += 1
average = float(average / N)
print ('The average is: ', average)

You can test the code in the online Python compiler in that link: Python compiler online.

While exercises Python - Second exercise

Let's do a second exercise using the while in Python.

Enter 10 numbers and add only those between 100 and 1000.

First we initialize i to 0, N to 10 and sum to 0. Next we check that each number is within the specified range. If the condition is true then we add the number to the others, otherwise not.

Here is therefore a possible solution to the proposed problem:

i, N = 0, 10
sum = 0
while i < N:
    n = int(input('Insert a number:'))
    if n >= 100 and n <= 1000:
        sum += n
    i += 1
print('The sum is: ', sum)

These are just simple exercises with the while in Python proposed for didactic purposes.


In this lesson we have done some exercises on the while loop in Python, in the next lesson we will create other interesting exercises.

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