How to Calculate the Area of a Triangle in Python

In this tutorial, we will program 'How to Calculate the Area of a Triangle in Python'. We will gain a better understanding of how to calculate the area of a triangle. The main goal here is to use a formula that will provide accurate results. I will provide a sample program to demonstrate the actual coding of this tutorial.

This topic is very easy to understand; just follow the instructions I provide, and you can also do it yourself with ease. The program I will show you covers the basics of programming for calculating the area of a triangle. I will do my best to provide you with the easiest method of creating this program, called 'Calculate the area of a triangel'. So, let's start with the coding.

Getting Started:

First you will have to download & install the Python IDLE's, here's the link for the Integrated Development And Learning Environment for Python https://www.python.org/downloads/.

Creating Main Function

This is the main function of the application. The following code will display a simple GUI in terminal console that will calculate the area of a triangle. To do this, simply copy and paste these blocks of code into the IDLE text editor.
  1. while True:
  2.    ret=False
  3.  
  4.    print("\n\n================= Calculate the Area of a Triangle =================\n\n")
  5.  
  6.  
  7.    a = int(input("Enter the A value: "))
  8.    b = int(input("Enter the B value: "))
  9.    c = int(input("Enter the C value: "))
  10.  
  11.  
  12.    s = (a + b + c) / 2
  13.  
  14.  
  15.    area = (s*(s-a)*(s-b)*(s-c)) ** 0.5
  16.    print('The area of the triangle is %0.2f' %area)
  17.  
  18.    user_input=input("\n\nTry Again? (Yes/No): ")
  19.    if user_input.lower()=='no':
  20.       print("Exit program.")
  21.       break
  22.  
  23.    elif user_input.lower()=='yes':
  24.       ret=True
  25.  
  26.    else:
  27.       print("Wrong input.")
  28.       ret=True
  29.  
  30.  
  31.    if ret:
  32.       continue

In the provided code, we simply enclosed the code with a while loop to allow for continuous execution of the program. To calculate the area of a triangle, we used a formula that will provide the correct result.

Output:

The How to Calculate the Area of a Triangle in Python source code that I provide can be download below. Please kindly click the download button.

There you have it we successfully created How to Calculate the Area of a Triangle in Python. I hope that this simple tutorial help you to what you are looking for. For more updates and tutorials just kindly visit this site. Enjoy Coding!

More Tutorials for Python Language

Python Tutorials

Add new comment