PYnative

Python Programming

  • Learn Python
    • Python Tutorials
    • Python Basics
    • Python Interview Q&As
  • Exercises
    • Python Exercises
    • C Programming Exercises
    • C++ Exercises
  • Quizzes
  • Code Editor
    • Online Python Code Editor
    • Online C Compiler
    • Online C++ Compiler
Home » Python » Programs and Examples » Python Programs to Calculate Area of Triangle

Python Programs to Calculate Area of Triangle

Updated on: April 17, 2025 | Leave a Comment

In this article, we will explore different ways to calculate the Area and Perimeter of a Triangle using Python, with detailed explanations and examples.

Table of contents

  • What is a Triangle?
  • Understand Area of a Triangle
  • 1. How to Calculate Area of a Triangle
  • 2. Calculate Area of Triangle Using User Inputs
  • 3. Calculate Area of Triangle Using a Function
  • 4. Calculate Area of Triangle Using Class (OOP)
  • 5. Calculate Area of Triangle Using Lambda
  • Summary

What is a Triangle?

A triangle is a three-sided polygon (2D shape) with three edges and three vertices. It is one of the basic shapes in geometry and has several properties that define its angles, sides, and area.

A triangle has a base (b) and a height (h), which are used to calculate the area.

Examples of Triangles in Real Life are Pizza slices, Pyramid structures, Roofs of houses, etc.

area of triangle

Understand Area of a Triangle

The area of a triangle is the amount of space enclosed within its three sides. It is measured in square units such as square centimeters (cm²), square meters (m²), or square inches (in²).

Formula to Calculate the Area of a Triangle:

Area = 1⁄2​ × Base × Height

  • Base (b) = Any side of the triangle used as a reference.
  • Height (h) = The perpendicular distance from the base to the opposite vertex.
  • Area (A): The total surface covered by the triangle, measured in square units (e.g., cm², m², inches²).

For Example, If a triangle has: Base = 10 cm, Height = 5 cm

Then, the Area is: Area = 1⁄2​ ​× 10 × 5 = 50⁄2 = 25 cm²

1. How to Calculate Area of a Triangle

Below are the steps to calculate the area of a triangle in Python:

  1. Define the Base and Height

    Assign values to base and height.
    For example, base = 10, height = 5

  2. Apply the Area Formula

    Use the formula: Area = 0.5 * base * height
    area = 0.5 * 10 * 5 = 25

  3. Mention the Correct Unit

    If the measurements are in meters, the area will be in square meters (m²).
    If the measurements are in centimetres, the area will be in square centimetres (cm²).
    If the measurements are in inches, the area will be in square inches (in²)

  4. Display the result

    Display the area and perimeter using the print() function

Code Example

# Step 1: Define base and height
base = 10
height = 5

# Step 2: Calculate area using the formula A = (1/2) * base * height
area = 0.5 * base * height

# Step 3: Display the result
print("Area of the triangle:", area, "square units")Code language: Python (python)

Output:

Area of the triangle: 25.0 square units

2. Calculate Area of Triangle Using User Inputs

If you want to calculate the area using the values provided by user then use the input() function. In this approach, we take the user’s input for the triangle’s base and height.

Note: As user inputs are by default in string format, we must convert them into floats for the calculations.

Code Example

# Step 1: Get user input for base and height
base = float(input("Enter the base of the triangle: "))
height = float(input("Enter the height of the triangle: "))

# Step 2: Calculate area using the formula A = (1/2) * base * height
area = 0.5 * base * height

# Step 3: Display the result
print("Area of the triangle:", area, "square units")


# Output:
# Enter the base of the triangle: 10
# Enter the height of the triangle: 5
# Area of the triangle: 25.0 square unitsCode language: Python (python)

3. Calculate Area of Triangle Using a Function

There are multiple advantages of using a function to calculate the area of a triangle as follows:

  • A function allows us to write the calculation once and use it multiple times without repeating code.
  • A function makes the code cleaner and more readable, improving maintainability.
  • Avoid errors: Using function we can keep formula in one place. It helps prevent mistakes
  • Easier Debugging & Updating: If the formula needs to be updated or changed, a function makes it easy to modify in one place.

In the example below, we calculated the area of two triangles by calling the same function.

Code Example:

def triangle_area(base, height):
    return 0.5 * base * height

triangle1 = triangle_area(10, 5)
print("Area of the triangle1:", triangle1, "square units")

triangle2 = triangle_area(20, 7)
print("Area of the triangle2:", triangle2, "square units")

# Output:
# Area of the triangle1: 25.0 square units
# Area of the triangle2: 70.0 square unitsCode language: Python (python)

4. Calculate Area of Triangle Using Class (OOP)

Object-Oriented Programming (OOP) is a structured way to write code by creating classes and objects. A class is a blueprint for creating objects, while an object is an instance of a class.

This approach provides better structure, reusability, and maintainability in your code. This approach is highly useful, especially for larger applications where multiple triangles need to be handled efficiently.

The following are the advantages of using OOP to calculate the area of a triangle:

  • Reusability: If you need to calculate the area of multiple triangles, you can create multiple objects.
  • Extensibility: With OOP, we can easily extend the class to calculate perimeter without affecting the existing structure.

Code Example

class Triangle:
    def __init__(self, base, height):
        self.base = base
        self.height = height

    def calculate_area(self):
        return 0.5 * self.base * self.height

# Creating an object of the Triangle class
triangle1 = Triangle(10, 5)
triangle2 = Triangle(20, 7)

# Printing the area
print("Area of the triangle1:", triangle1.calculate_area(), "square units")
print("Area of the triangle2:", triangle2.calculate_area(), "square units")


# Output:
# Area of the triangle1: 25.0 square units
# Area of the triangle2: 70.0 square unitsCode language: Python (python)

Explanation

  • First Define a Class
    • Define a class named Triangle.
    • The class will store the base and height of the triangle.
  • Now, Create a Constructor using the __init__ method
    • The constructor (__init__) initializes the base and height when an object is created.
    • The self keyword refers to the current instance of the class.
  • Now, Create a Method to Calculate Area
    • Define a method calculate_area() inside the class.
    • This method returns the area using the formula: Area = 0.5 * Base * Height
  • Now, Create an Object of the Class
    • Use triangle1 = Triangle(10, 5) to create a triangle with: base = 10, height = 5
    • Use triangle2 = Triangle(20, 7) to create a triangle with: base = 20, height = 7
  • In the end, call the mkethod to get the area and print it
    • Use calculate_area() to get the area.
    • Store the result in a variable and display it using print().

5. Calculate Area of Triangle Using Lambda

A lambda function in Python is a small, anonymous function that can have multiple arguments but only one expression, which is evaluated and returned. For a more compact implementation, you can use a lambda function.

A lambda function syntax: lambda arguments: expression

  • lambda → Keyword to define the function.
  • arguments → Input parameters (like a normal function).
  • expression → A single operation that returns a result.

Code Example

triangle_area = lambda base, height: 0.5 * base * height

# Example usage
print("Area of the triangle:", triangle_area(10, 5), "square units")

# Output:
# Area of the triangle: 25.0 square unitsCode language: Python (python)

Explanation

  • base and height are the input parameters.
  • 0.5 * base * height is the calculation expression.
  • triangle_area is the name to call the anonymous lambda function.

Summary

Calculating the area of a triangle in Python is a straightforward task with multiple flexible approaches. Whether you’re using basic arithmetic, user input, functions, object-oriented programming, or lambda expressions, each method offers a clear way to apply the logic effectively.

These approaches reinforce core programming skills and make your code modular, reusable, and scalable. Choosing the right method depends on your specific use case, whether it’s a quick calculation or part of a larger application.

Filed Under: Programs and Examples, Python, Python Basics

Did you find this page helpful? Let others know about it. Sharing helps me continue to create free Python resources.

TweetF  sharein  shareP  Pin

About Vishal

I’m Vishal Hule, the Founder of PYnative.com. As a Python developer, I enjoy assisting students, developers, and learners. Follow me on Twitter.

Related Tutorial Topics:

Programs and Examples Python Python Basics

All Coding Exercises:

C Exercises
C++ Exercises
Python Exercises

Python Exercises and Quizzes

Free coding exercises and quizzes cover Python basics, data structure, data analytics, and more.

  • 15+ Topic-specific Exercises and Quizzes
  • Each Exercise contains 25+ questions
  • Each Quiz contains 25 MCQ
Exercises
Quizzes

Leave a Reply Cancel reply

your email address will NOT be published. all comments are moderated according to our comment policy.

Use <pre> tag for posting code. E.g. <pre> Your entire code </pre>

In: Programs and Examples Python Python Basics
TweetF  sharein  shareP  Pin

 Explore Python

  • Python Tutorials
  • Python Exercises
  • Python Quizzes
  • Python Interview Q&A
  • Python Programs

  Python Tutorials

  • Get Started with Python
  • Python Statements
  • Python Comments
  • Python Keywords
  • Python Variables
  • Python Operators
  • Python Data Types
  • Python Casting
  • Python Control Flow statements
  • Python For Loop
  • Python While Loop
  • Python Break and Continue
  • Python Nested Loops
  • Python Input and Output
  • Python range function
  • Check user input is String or Number
  • Accept List as a input from user
  • Python Numbers
  • Python Lists
  • Python Tuples
  • Python Sets
  • Python Dictionaries
  • Python Functions
  • Python Modules
  • Python isinstance()
  • Python OOP
  • Python Inheritance
  • Python Exceptions
  • Python Exercise for Beginners
  • Python Quiz for Beginners

All Python Topics

  • Python Basics
  • Python Exercises
  • Python Quizzes
  • Python File Handling
  • Python Date and Time
  • Python OOP
  • Python Random
  • Python Regex
  • Python Pandas
  • Python Databases
  • Python MySQL
  • Python PostgreSQL
  • Python SQLite
  • Python JSON

About PYnative

PYnative.com is for Python lovers. Here, You can get Tutorials, Exercises, and Quizzes to practice and improve your Python skills.

Follow Us

To get New Python Tutorials, Exercises, and Quizzes

  • Twitter
  • Facebook
  • Sitemap

Explore Python

  • Learn Python
  • Python Basics
  • Python Databases
  • Python Exercises
  • Python Quizzes
  • Online Python Code Editor
  • Python Tricks

Coding Exercises

  • C Exercises
  • C++ Exercises
  • Python Exercises

Legal Stuff

  • About Us
  • Contact Us

We use cookies to improve your experience. While using PYnative, you agree to have read and accepted our:

  • Terms Of Use
  • Privacy Policy
  • Cookie Policy

Copyright © 2018–2026 pynative.com