Python if example

In this lesson we try to implement a simple Python if example, to learn more about using conditional statements.

I take three numbers as input and check if they can represent the length of the three sides of a triangle. Then we determine if the triangle having the indicated lengths as sides is equilateral, isosceles or scalene.

We have also implemented this same program in Scratch: triangles with Scratch and with Algobuild: triangles with Algobuild. Also in C language we have proposed a possible solution: triangles in C.

Implementation of the Python if example

First of all we take the three sides as input and store them in the variables side1, side2 and side3.

After we check these conditions:

side1 < side2 + side3
side2 < side1 + side3
side3 < side2 + side1

If all three are verified, we proceed with the check on the equality of the sides, otherwise we display a message in the output that warns the user that the data entered cannot represent the sides of a triangle.

So if they can be the sides of a triangle, we can immediately check if they are all three equal (equilateral triangle) or if at least two are equal (isosceles triangle) or if they are all different (scalene triangle).

Here is the complete code of the example Python if:


print ('Hi, today we will create a small program on triangles')
side1 = int(input('Insert the first side of a triangle:'))
side2 = int(input('Insert the second side of a triangle:'))
side3 = int(input('Enter the third side of a triangle:'))
if side1 < side2 + side3 and side2 < side1 + side3 and side3 < side2 + side1:
    if side1 == side2 and side2 == side3:
        print('The triangle is equilateral')
    elif side1 == side2 or side2 == side3 or side3 == side1:
        print('The triangle is isosceles')
   else:
       print('The triangle is scalene')
else:
    print('The sides inserted cannot be those of a triangle')

The algorithm can be solved in various ways.

I have shown just a very simple example of Python if, a program that determines whether it is possible to construct a triangle by evaluating the sides.
This example allows you to learn more about the use of conditional instructions and logical operators.

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 *