๐ Day 21/150 – Perimeter of a Rectangle in Python
Understanding how to calculate the perimeter of a rectangle is one of the simplest yet important concepts in programming. It helps you build a strong foundation in working with formulas, user input, and functions in Python.
The formula for the perimeter of a rectangle is:
Let’s explore different ways to implement this in Python ๐
๐น Method 1 – Direct Calculation
This is the simplest way where we directly assign values to length and width.
length = 10 width = 5 perimeter = 2 * (length + width) print("Perimeter of rectangle:", perimeter)
๐ง Explanation:
- We define length and width.
- Apply the formula: 2 * (length + width)
- Print the result.
๐ Best for: Beginners and quick calculations.
๐น Method 2 – Taking User Input
This method makes your program interactive by allowing users to enter values.
length = float(input("Enter length: ")) width = float(input("Enter width: ")) perimeter = 2 * (length + width) print("Perimeter of rectangle:", perimeter)
๐ง Explanation:
- input() takes user input.
- float() converts input into decimal numbers.
- Same formula is applied afterward.
๐ Best for: Real-world applications where input varies.
๐น Method 3 – Using a Function
Functions make your code reusable and clean.
def find_perimeter(l, w): return 2 * (l + w) print(find_perimeter(10, 5))
๐ง Explanation:
- def is used to define a function.
- l and w are parameters.
- return sends back the calculated value.
๐ Best for: Writing modular and reusable code.
⚡ Key Takeaways
- The formula is simple: 2 × (length + width)
- Use direct values for quick tasks.
- Use input() for interactive programs.
- Use functions for clean and reusable code.
.png)
.png)
.png)
