
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
- We first take the side length as input.
- Now, use the formula for perimeter = 4 Ã side.
- 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
- Create a function that calculates the perimeter using the formula.
- Pass the input side length as an argument to the function.
- 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)