In this lesson I propose some examples on the while in Python, in order to consolidate the argument on iterations.

First example on the while in Python

Input data 10 numbers count how many even and how many odd numbers have been entered.

To count the even and odd numbers we therefore use two variables. We call them, for example, contap and contap. Therefore, if we insert an even number we increase contap, otherwise we increase contap.

So the algorithm could be solved in this way:


i = count_e = count_o = 0
while i < 10:
   n = int(input('Insert a number:'))
   if n % 2 == 0:
       conta_e + = 1
   else:
       count_o + = 1
   i += 1
print('The even numbers entered are:', count_e)
print('The odd numbers entered are:', count_o)

Let's assume now that we want to exclude the number zero from the count of even numbers, simply for educational purposes, since in any case zero is considered an even number. How can we change the algorithm?


i = count_e = count_o = 0
while i < 10:
   n = int(input('Insert a number:'))
   if n != 0:
      if n % 2 == 0:
          conta_e += 1
      else:
          count_o += 1
   i += 1
print('The even numbers entered are:', count_e)
print('The odd numbers entered are:', count_o)

Let's make a further modification by now counting how many numbers equal to zero have been entered.


i = count_d = count_p = count_z = 0
while i < 10:
   n = int(input('Insert a number:'))
   if n == 0:
      count_z += 1
   elif n % 2 == 0:
      conta_e += 1
   else:
      count_o += 1
   i += 1
print ('The even numbers entered are:', count_e, 'The odd numbers entered are:', count_o, 'The numbers equal to zero are:', count_z)

Second example on the while in Python

Calculate and view the 2 times table.

The first procedure that makes use of a single variable can be this:


i = 0

while i <= 20:
    print(i)
    i += 2

We initialized the variable i to 0 and increased it by two at each iteration until the condition i <= 20 is true.

But we can also think of another possible solution where we use a variable i that we multiply by two.

This variable increases for each operation by 1 until it reaches 10.


i = 0

while i <= 10:
    n = i*2
    print(2, 'x', i, '=', n)
    i += 1

We could also define a constant value so as to easily modify the table.


i = 0
t = 2

while i <= 10:
   n = i*t
   print(t, 'x', i, '=', n)
   i += 1

In this way, for example, if we wanted to create the table of 9, it would be enough to change t = 2 with t = 9.

In the next lesson we will cover yet more examples of the while loop in Python.

Some useful links

Python tutorial

Python Compiler

Install Python

Variables

Assignment operators

Strings

Casting

How to find the maximum of N numbers

How to use the math module

Bubble sort

Matplotlib Plot