π 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)

0 Comments:
Post a Comment