Python while loop exercises

Let’s improve our knowledge in Python with some while loop exercises.

In particular, today we will face an exercise that also deals with the exchange of variables as a topic.

Python while loop exercises – first exercise

Write a program that, by reading two integers, subtracts the lesser from the greater until their difference becomes less than 3 units, displaying the result of each iteration on the screen.

Let’s take an example by taking 2 values ​​a = 20 and b = 7.

In this case, being a greater than b, we will proceed with these operations:

20 – 7 = 13 is not less than 3 so we continue to subtract

13 – 7 = 6 is not less than 3 so we continue to subtract

6 – 7 = -1 the difference is less than 3, so we stop.

First of all we ask as input the two numbers a and b integers.

Then with a conditional statement we check if a is smaller than b.

If it is true we exchange the values.

Subsequently we store in d the difference between a and b.

Then with a while loop, that continues until the difference is less than 3, we continue to subtract b from a. Therefore, we only establish the major at the beginning of the procedure, after which we continue to subtract.

Python while loop exercises – Here is a possible implementation of the code:


a = int(input('Enter the number a:'))
b = int(input('Enter the number b:'))

if a < b:
    a, b = b, a
d = a - b

while d>3
    print(d)
    d = d - b

We can leave out the case where a and b are equal as the while loop will not be executed anyway.

However, if we want to display an output message that the two numbers are the same then we should add another condition.

Test the code in the online Python compiler online in this link: Python compiler.

Conclusion

Python while loop exercises allow us to learn more confidently how to use iterative structures, in the next lessons we will develop many other exercises.

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

Lascia un commento

Il tuo indirizzo email non sarà pubblicato. I campi obbligatori sono contrassegnati *