w3resource

Python: How to calculate area of a triangle in Python?


Triangle Area Calculator

Write a Python program that will accept the base and height of a triangle and compute its area.

Python: Area of a triangle

A triangle is a polygon with three edges and three vertices. It is one of the basic shapes in geometry. A triangle with vertices A, B, and C is denoted triangle ABC.

  • Vertex of a triangle: The point at which two sides of a triangle meet.
  • Altitude of a triangle: The perpendicular segment from a vertex of a triangle to the line containing the opposite side.
  • Base of a triangle: The side of a triangle to which an altitude is drawn.
  • Height of a triangle: The length of an altitude.

Python: Area of a triangle

Sample Solution:

Python Code:

# Prompt the user to input the base and height of a triangle as integers.
b = int(input("Input the base : "))
h = int(input("Input the height : "))

# Calculate the area of the triangle using the formula: (base * height) / 2.
area = b * h / 2

# Print the calculated area of the triangle.
print("area = ", area)

Sample Output:

Input the base : 20                                                                                           
Input the height : 40                                                                                         
area =  400.0   

Explanation:

The said code prompts the user to input an integer value for the base and height of a triangle. Stores these values in variables "b" and "h" respectively. It then calculates the area of the triangle by multiplying the base and height and dividing the result by 2 and assigns the result to the variable "area". Finally, it prints the calculated area.

Flowchart:

Flowchart: Accept the base and height of a triangle and compute the area.

Python Code Editor:

 

Previous: Write a Python program to print out a set containing all the colors from a list which are not present in another list.
Next: Write a Python program to compute the greatest common divisor (GCD) of two positive integers.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.