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, Perimeter, Diagonal of Rectangle

Python Programs to Calculate Area, Perimeter, Diagonal of Rectangle

Updated on: April 17, 2025 | Leave a Comment

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

Table of contents

  • What is Rectangle?
  • 1. How to Calculate Area, Perimeter and Diagonal of a Rectangle
  • 2. Calculate Using User Inputs
  • 3. Calculate Using a Function
  • 4. Calculate Using Class (OOP)
  • 5. Calculate Using Lambda
  • Summary

What is Rectangle?

In simple terms, a rectangle is a flat, four-sided polygon shape where:

  • All four internal angles are right angles (90 degrees). This is the defining characteristic.  
  • It has four straight sides.
  • Opposite sides are parallel and equal in length. 
area of rectangle

Examples of Rectangles in Real Life are Mobile Phones, Computer Screens, Books, Doors, etc.

We define a rectangle using length and width.

  1. Length (L): The longer side of the rectangle.
  2. Width (W): The shorter side of the rectangle

Now, let’s understand Area, Perimeter, and Diagonal of a Rectangle.

Area of Rectangle

The area of a rectangle is the amount of space enclosed within its four sides.

Formula to Calculate the Area of a Rectangle

Area = Length × Width

Area (A): The total surface covered by the rectangle, measured in square units (e.g., cm², m², inches²).

For Example, If a rectangle has: Length = 10 meters, Width = 5 meters, then, the Area is: 10 × 5 = 50 m²

Perimeter of a Rectangle

The perimeter of a rectangle is the total length of its boundary. It is calculated by adding the lengths of all four sides.

Formula to Calculate the Perimeter of a Rectangle:

Perimeter = 2 × ( Length + Width )

For Example, Assume rectangle has: Length = 10 meters, Width = 5 meters, then perimeter is: P = 2 × ( 10 + 5 ) = 2 × 15 = 30 meters

Diagonal of a Rectangle

The diagonal of a rectangle is the straight-line distance between opposite corners (vertices) of the rectangle. It divides the rectangle into two right-angled triangles.

Formula to Calculate the Diagonal of a Rectangle:

The diagonal (d) of a rectangle can be found using the Pythagorean Theorem, since a rectangle forms a right triangle when the diagonal is drawn:

d = √(L² + W²)
  • d = Diagonal
  • L = Length of the rectangle
  • W = Width of the rectangle
  • √ = Square root function

For Example, If a rectangle has: Length = 10 meters, Width = 5 meters

1. How to Calculate Area, Perimeter and Diagonal of a Rectangle

Steps to find the Area of a Rectangle in Python:

  1. Identify the Dimensions

    Length (L) – The longer side of the rectangle.
    Width (W) – The shorter side of the rectangle.

  2. Calculate the Area using the below formula

    Area = Length × Width

  3. Calculate the Perimeter using the below formula

    Perimeter = 2 × ( Length + Width )

  4. Calculate the Diagonal using the below formula

    In Python, diagonal = math.sqrt( length ** 2 + width ** 2 )
    Here, the square of length and width is calculated using the Exponentiation operator (**) and added.

    The square root is computed using math.sqrt() function. The math.sqrt() function returns the square root of a given non-negative number.

  5. Mention the Correct Unit

    If the length and width are in meters, the Area will be in square meters (m²).
    The Perimeter and Diagonal are in meters (m). Likewise for other units like cm, inch, etc.

  6. Display the result

    Display the area, Perimeter, and Diagonal using the print() function

Code Example

import math

# length and width measurement
length = 10
width = 5

# Calculate Area
area = length * width

# Calculate Perimeter
perimeter = 2 * (length + width)

# Calculate Diagonal
diagonal = math.sqrt(length**2 + width**2)

# Display the result
print(f"Area is {area} square units. Perimeter is {perimeter} units. Diagonal is {diagonal} units.")Code language: Python (python)

Output:

Area is 50 square units. Perimeter is 30 units. Diagonal is 11.180339887498949 units.

2. Calculate Using User Inputs

If you want to calculate area using the length and width specified by user then use the input() function.

The input() function allow us to get input from the user while a Python script is running. It pauses the execution of your program and waits for the user to type something into the console (or terminal) and press the Enter key.

The input() always returns the user’s input as a string, regardless of whether the user typed numbers, letters, or symbols. So you must convert it to numbers using the float() function.

Taking input from the user dynamically allows flexibility.

Code Example

import math

# Step 1: Take input and convert it to float
length = float(input("Enter the length of the rectangle: "))
width = float(input("Enter the width of the rectangle: "))

# Step 2: Use the formula
area = length * width                       # Area formula
perimeter = 2 * (length + width)            # Perimeter formula
diagonal = math.sqrt(length**2 + width**2)  # Diagonal formula

# Step 3: Display the result
print(f"Area is {area} square units. Perimeter is {perimeter} units. Diagonal is {diagonal} units.")Code language: Python (python)

Output:

Enter the length of the rectangle: 10
Enter the width of the rectangle: 5

Area is 50.0 square units. Perimeter is 30.0 units. Diagonal is 11.180339887498949 units.

3. Calculate Using a Function

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

  • Encapsulating the calculation in a function makes the code reusable i.e., we can use it multiple times without repeating code.
  • A function makes the code cleaner and more readable, improving maintainability.
  • Avoid errors: A function helps prevent mistakes by keeping the formula in one place.
  • 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 have different functions to calculate area, perimeter, and diagonal, which can be reused for multiple rectangles without repeating the code.

Code Example

import math

# Function to calculate area
def rectangle_area(length, width):
    return length * width

# Function to calculate perimeter
def rectangle_perimeter(length, width):
    return 2 * (length + width)

# Function to calculate the diagonal
def rectangle_diagonal(length, width):
    return math.sqrt(length**2 + width**2)

# Example usage
length = 10
width = 5

area = rectangle_area(length, width)
perimeter = rectangle_perimeter(length, width)
diagonal = rectangle_diagonal(length, width)

# Display the result
print(f"Area is {area} square units. Perimeter is {perimeter} units. Diagonal is {diagonal} units.")


# Output:
# Area is 50 square units. Perimeter is 30 units. Diagonal is 11.180339887498949 units.Code language: Python (python)

4. Calculate 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 rectangles need to be handled efficiently.

The following are the advantages of using OOP to calculate the area, perimeter and diagonal of a rectangle:

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

Code Example

import math

# Define a class named Rectangle
class Rectangle:
    # Constructor to initialize length and width
    def __init__(self, length, width):
        self.length = length
        self.width = width

    # Method to calculate area
    def calculate_area(self):
        return self.length * self.width

    # Method to calculate perimeter
    def calculate_perimeter(self):
        return 2 * (self.length + self.width)

    # Method to calculate diagonal
    def calculate_diagonal(self):
        return math.sqrt(self.length ** 2 + self.width ** 2)


# Create an object of the Rectangle class
rect = Rectangle(10, 5)

# Call the methods
area = rect.calculate_area()
perimeter = rect.calculate_perimeter()
diagonal = rect.calculate_diagonal()

# Display the result
print(f"Area is {area} square units. Perimeter is {perimeter} units. Diagonal is {diagonal} units.")


# Output:
# Area is 50 square units. Perimeter is 30 units. Diagonal is 11.180339887498949 units.Code language: Python (python)

Explanation

  • Define a Class
    • Define a class named Rectangle.
    • The class will store the length and width of the rectangle.
  • Create a Constructor (__init__ method)
    • The constructor (__init__) initializes the length and width when an object is created.
    • The self keyword refers to the current instance of the class.
  • Create a Method to Calculate Area
    • Define a method calculate_area() inside the class.
    • This method returns the area using the formula: Area = Length * Width
  • Create a Method to Calculate Perimeter
    • Define a method calculate_perimeter() inside the class.
    • This method returns the perimeter using the formula: 2 × ( Length + Width )
  • Create a Method to Calculate Diagonal
    • Define a method calculate_diagonal() inside the class.
    • This method returns the diagonal using the formula: d = math.sqrt(self.length**2 + self.width**2)
  • Create an Object of the Class
    • Use rect = Rectangle(10, 5) to create a rectangle with: length = 10, width = 5
  • Call the Method to get the Area, Perimeter and Diagonal
    • Use rect.calculate_area() to get the area.
    • Use rect.calculate_perimeter() to get the perimeter.
    • Use rect.calculate_diagonal() to get the diagonal.
  • Store the result in a variable and display it using print().

5. Calculate 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 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

import math

length = 10
width = 5

rectangle_area = lambda length, width: length * width

rectangle_perimeter = lambda length, width: 2 * (length + width)

rectangle_diagonal = lambda length, width: math.sqrt(length**2 + width**2)

# Call the methods
area = rectangle_area(length, width)
perimeter = rectangle_perimeter(length, width)
diagonal = rectangle_diagonal(length, width)

# Display the result
print(f"Area is {area} square units. Perimeter is {perimeter} units. Diagonal is {diagonal} units.")


# Output:
# Area is 50 square units. Perimeter is 30 units. Diagonal is 11.180339887498949 units.Code language: Python (python)

Explanation

  • length and width are the input parameters.
  • To calculate Area:
    • length * width is the calculation expression.
    • rectangle_area is the name to call the anonymous lambda function.
  • To calculate Perimeter:
    • 2 * (length + width) is the calculation expression.
    • rectangle_perimeter is the name to call the anonymous lambda function.
  • To calculate Diagonal:
    • math.sqrt(length**2 + width**2) is the calculation expression.
    • rectangle_diagonal is the name to call the anonymous lambda function.

Summary

Calculating a rectangle’s area, perimeter, and diagonal in Python is simple and efficient, with multiple approaches that suit different programming needs. Whether you’re using basic arithmetic, user input, functions, object-oriented programming, or lambda functions, each method effectively applies the core formula.

Choose the approach that best fits your task—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