DEV Community

CharlesTechy
CharlesTechy

Posted on

A program to calculate the area of a triangle using python

Yo! guys today am dropping a snippet to calculate the area of a triangle using Python Programming..

Just like other programming languages like; C++, Java, JavaScript and the rest you can do a lot of mathematical stuff with the Python Lang.

Tho forks may not want to do this but will like to just work with another approach other than this.

1. The First thing to do is to print a message on the screen telling the user about your program.

Using the print statement in Python, we can easily print messages to the user's screen.

print ("A Program to calculate the Area of a Triangle");

2. The next thing to do is to wait for the user's command, by printing on the screen press any button to continue.

input("Press any button to continue...");

with python version 2.x we can easily use

raw_input("Press any button to continue");

3. Tell the user to enter the base of the angle, which will be stored in a variable called 'angleBase'.

angleBase = input("Enter Angle Base\n");

4. Request for the height of the angle, which will be stored in a variable called 'angleHeight'.

angleHeight = input("Enter Angle Height\n");

5. I then declared two variables called 'isHeightANumber' and 'isBaseANumber' and assigned them to the language(Python)'s function called "isdigit()".

isHeightANumber = angleHeight.isdigit();
isBaseANumber = angleBase.isdigit();
Enter fullscreen mode Exit fullscreen mode

What is the work of isdigit()?

"isdigit()" is a python function which checks if a variable value(s) are/is a digit(s).

The last part of the code is shown below

Before Processing/ Calculating the user data, i tried to verify that the fields are not empty or void by using the

if statement and the not equal (!=) operator

if angleBase!="" and angleHeight!="":

Also i consider checking and validating by making sure what the user entered is a number by using the

if statment and isdigit()
if isBaseANumber and isHeightANumber:

The last part is all about declaring a variable called areaOfATriangle which will calculate the area of the input entered by the user, if the base and height entered by the user are/is a number, it will print out the area of the triangle, if not it will show the

else statement

which says "Angle Base and Height must be a number"

areaOfATriangle = int(int(angleBase) * int(angleHeight) / int(2));

print("Area of a triangle whose base = ", angleBase, " and height = ", angleHeight, " is = ", areaOfATriangle);


else:
       print("Angle Base and Height must be a number");
else:
       print("Height and Base can't be empty.");
Enter fullscreen mode Exit fullscreen mode

Top comments (0)