Exercises Python if statement

In this lesson we propose some exercises on Python if statement, in order to consolidate what has been studied.

First exercise on Python if statement

Given in input the numerator and denominator of a fraction, establish whether this fraction is proper, improper or apparent.

For the resolution of this algorithm we remember the definitions listed below.

A fraction is proper when the numerator is less than the denominator.

On the other hand, a fraction is improper when the numerator is greater than the denominator but is not a multiple of it, as otherwise it would be apparent.

Finally, a fraction is apparent when the numerator equals the denominator or is a multiple of the denominator.

Here is a possible solution that makes use of conditional statements in Python, where we consider the numerator and denominator integers.


numerator, denominator = int(input('Insert the numerator:')), 
int(input('Insert the denominator:'))

if numerator == denominator or numerator% denominator == 0:
    print('apparent fraction')
else:
    if numerator> denominator:
        print('improper fraction')
    else:
        print('proper fraction')

Now try to find another possible solution to the proposed algorithm.

Second exercise on Python if statement

Determine, without carrying out the operation, if the product of two natural numbers is equal to zero.

The product of two natural numbers equals zero when at least one of the numbers equals zero.

So for the resolution it is convenient for us to use the logical operator or.


a, b = int(input('Insert a:')), 
int(input('Insert b:'))

if a == 0 or b == 0:
    print('the product is null')
else:
   print ('the product is not null')

We could also not use the or by implementing this solution that makes use of elif (else if).


a, b = int(input('Insert a:')), 
int(input('Insert b:'))

if a == 0:
    print('the product is null')
elif b == 0:
    print('the product is null')
else:
    print('the product is not null')

Clearly these are just some exercises on Python if statement, in the next lessons we will practice again.

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 *