Find Perimeter of Square in Python



A square is a closed two-dimensional figure having 4 equal sides. Each angle of a square is 90 degrees. The perimeter of a square is the sum of all its sides.

Problem Description

In this problem, we are given the side of a square, and we have to find the perimeter of the square. In this tutorial, we are going to find the perimeter of a given square in Python using different approaches.

Example 1

  • Input: side = 6 units
  • Output: 24 units

Explanation

Using the formula to calculate the perimeter of the square: 4 × side = 4 × 6 = 24 units

Example 2

  • Input: side = 0 units
  • Output: 0 units

Explanation

If the side length is zero, the square does not exist as a two-dimensional figure, and hence, there is no perimeter.

Example 3

  • Input: side = 12 units
  • Output: 48 units

Explanation

Using the formula to calculate the perimeter of the square: 4 × side = 4 × 12 = 48 units

Below are different approaches to find the perimeter of the square

  • Using Direct Formula Approach
  • Using Function

Using Direct Formula Approach

We use the direct formula to calculate the perimeter of the square. The formula for calculating the perimeter is: Perimeter = 4 × side. After calculating the perimeter, we return the result.

Steps for Implementation

  1. We first take the side length as input.
  2. Now, use the formula for perimeter = 4 × side.
  3. Return the calculated perimeter.

Implementation Code

# Take the side length as input
side = 5

# Calculate the perimeter using the formula
perimeter = 4 * side

print(f"The perimeter of the square with side {side} is: {perimeter}")

Output

The perimeter of the square with side 5 is: 20

Time Complexity: O(1)
Space Complexity: O(1)

Using a Function

We use a function to calculate the perimeter of the square. The logic and formula remain the same, but encapsulating the logic in a function makes it reusable and more modular.

Steps for Implementation

  1. Create a function that calculates the perimeter using the formula.
  2. Pass the input side length as an argument to the function.
  3. Output the calculated result.

Implementation Code

# Function to calculate the perimeter of a square
def calculate_perimeter(side):
    return 4 * side

# Input: side length of the square
side = 6

# Call the function
perimeter = calculate_perimeter(side)

# Output
print(f"The perimeter of the square with side length {side} is: {perimeter}")

Output

The perimeter of the square with side length 6 is: 24

Time Complexity: O(1)
Space Complexity: O(1)

Updated on: 2025-01-15T18:45:19+05:30

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements