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 and Diagonal of Square

Python Programs to Calculate Area, Perimeter and Diagonal of Square

Updated on: April 17, 2025 | Leave a Comment

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

Table of contents

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

What is a Square

A square is a four-sided polygon (quadrilateral) where:

  1. All four sides are equal in length.
  2. All four angles are 90 degrees (right angles).
  3. The opposite sides are parallel to each other.
  4. Both diagonals are equal in length and bisect each other at 90 degrees.
square area

Examples of Squares in Real Life are Chessboard, Tiles on a floor, etc.

Understand the Area of a Square

The area of a square is the amount of space enclosed within its four equal 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 Square:

Area = Side²

  • Side (S) = Length of one side of the square
  • Area is always expressed in square units (e.g., cm², m², in²).

For Example,

  • If a square has a side length of 5 meters: Area = 5² = 25 m²
  • If a square has a side length of 4.5 cm: Area = 4.5² = 20.25 cm²

Understand the Perimeter of a Square

The perimeter of a square is the total length of its boundary. It is the sum of all four equal sides of the square.

The formula for the Perimeter of a Square:

Perimeter = 4 × Side

  • Side (S) = The length of one side of the square.
  • Perimeter (P) = The total length around the square.

For Example, If a square has a side length of 6 meters:
Then, the perimeter is: Perimeter = 4 × 6 = 24 meters

Understand the Diagonal of a Square

The diagonal of a square is the straight line connecting two opposite corners (vertices) of the square. Every square has two diagonals, and they are:

  • Equal in length
  • Perpendicular to each other
  • Bisect each other at 90°

Diagonal Formula:

Diagonal = √2 ​× Side

Where:

  • Side = the length of one side of the square
  • √2 ≈ 1.4142

For Example, If the side of a square is 4 cm, then:
Diagonal = √2​ × 4 ≈ 1.4142 × 4 = 5.6568 cm

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

Below are the steps to find the Area, Perimeter and Diagonal of a Square in Python:

  1. Identify the Side Length

    A square has four equal sides.

  2. Apply Area Formula

    The formula to calculate the area of a square is: Area = Side²
    If Side = 5 meters, then: Area = 5² = 5 × 5 = 25 m²

  3. Apply the Perimeter Formula

    The formula to calculate the Perimeter of a Square is: perimeter = 4 * side
    If side = 10 meters, then: perimeter = 4 × ( 10 ) = 40 meters

  4. Apply Diagonal Formula

    The formula to calculate the diagonal of a square is: diagonal = √2 ​× Side

    In Python, diagonal = math.sqrt(2) * side
    The square root of 2 is calculated 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 side length is in meters (m), → Area is in square meters (m²), 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

side = 5  # Length of one side
area = side * side              # Area formula
perimeter = 4 * side            # Perimeter formula
diagonal = math.sqrt(2) * side  # Diagonal formula

print(f"Area is {area} square units, Perimeter is {perimeter} units, Diagonal is {diagonal} units")Code language: Python (python)

Output:

Area is 25 square units, Perimeter is 20 units, Diagonal is 7.0710678118654755 units

2. Calculate Using User Inputs

If you want to calculate area using the value specified by user then use the input() function. As the input is in string format, we must convert it into a float for the calculations.

Taking input from the user dynamically allows flexibility.

Code Example

import math

side = float(input("Enter the side length of the square: "))
area = side * side              # Area formula
perimeter = 4 * side            # Perimeter formula
diagonal = math.sqrt(2) * side  # Diagonal formula

print(f"Area is {area} square units, Perimeter is {perimeter} units, Diagonal is {diagonal} units")Code language: Python (python)

Output:

Enter the side length of the square: 5
Area is 25.0 square units, Perimeter is 20.0 units, Diagonal is 7.0710678118654755 units

3. Calculate Using a Function

There are multiple advantages of using a function to calculate the area, perimeter and diagonal of a square as follows:

  • Encapsulating the calculation in a function makes the code reusable and modular.
  • A function allows us to write the calculation once and use it multiple times without repeating code.
  • If a program requires multiple area calculations, a function makes it scalable.
  • 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 squares without repeating the code.

Code Example

import math

# Function to calculate the Area
def square_area(side):
    return side * side

# Function to calculate the Perimeter
def square_perimeter(side):
    return 4 * side

# Function to calculate the Diagonal
def square_diagonal(side):
    return math.sqrt(2) * side

# Function calls
side = 5
area = square_area(side)     
perimeter = square_perimeter(side)
diagonal = square_diagonal(side)

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


# Output:
# Area is 25 square units, Perimeter is 20 units, Diagonal is 7.0710678118654755 unitsCode language: Python (python)

4. Calculate Area of Square 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 squares need to be handled efficiently.

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

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

Code Example

import math

class Square:
    def __init__(self, side):
        self.side = side  # Initialize side length

    # Method to calculate the Area
    def calculate_area(self):
        return self.side * self.side

    # Method to calculate the Perimeter
    def calculate_perimeter(self):
        return 4 * self.side

    # Method to calculate the Perimeter
    def calculate_diagonal(self):
        return math.sqrt(2) * self.side


side = 5    # length of side
sq = Square(side)   # object of Square class

# method calls
area = sq.calculate_area()
perimeter = sq.calculate_perimeter()
diagonal = sq.calculate_diagonal()

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


# Output:
# Area is 25 square units, Perimeter is 20 units, Diagonal is 7.0710678118654755 units
Code language: Python (python)

Explanation

  • Define a Class
    • Define a class named Square.
    • The class will store the side of the square.
  • Create a Constructor (__init__ method)
    • The constructor (__init__) initializes the side 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 = Side²
  • Create a Method to Calculate Perimeter
    • Define a method calculate_perimeter() inside the class.
    • This method returns the perimeter using the formula: 4 × ( side )
  • 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(2) * side
  • Create an Object of the Class
    • Use sq = Square(5) to create a square with: side = 5
  • Call the Methods to get the Area, Perimeter and Diagonal
    • Use sq.calculate_area() to get the area of the object.
    • Use sq.calculate_perimeter() to get the perimeter of the object.
    • Use sq.calculate_diagonal() to get the diagonal of the object.
  • 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 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

import math

square_area = lambda side: side * side
square_perimeter = lambda side: 4 * side
square_diagonal = lambda side: math.sqrt(2) * side

side = 5    # length of side
area = square_area(side)
perimeter = square_perimeter(side)
diagonal = square_diagonal(side)

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


# Output:
# Area is 25 square units, Perimeter is 20 units, Diagonal is 7.0710678118654755 units
Code language: Python (python)

Explanation

  • side is the input parameter.
  • To calculate Area:
    • side ** 2 is the calculation expression.
    • square_area is the name to call the anonymous lambda function.
  • To calculate Perimeter:
    • 4 * side is the calculation expression.
    • square_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 the area, perimeter and diagonal of a square in Python is simple and efficient, with multiple approaches to 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

Image

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

Advertisement
Advertisement