The task of calculating the Area of a Rectangle in Python involves taking the length and width as input, applying the mathematical formula for the area of a rectangle, and displaying the result.
Area of Rectangle Formula :
Area = Width * Height
Where:
- Length is the longer side of the rectangle.
- Width is the shorter side of the rectangle.
For example, if Length = 5 and Width = 8, the area is calculated as Area=5×8=40.
Using * operator
The direct multiplication approach is the most efficient way to find the area of a rectangle . It involves multiplying the length and width directly using the * operator.
x = 5 # length
y = 8 # width
res = x * y
print(res)
Output
40
Explanation: This code calculates the area of a rectangle using the formula length * width. Here, x = 5 represents the length and y = 8 represents the width. The multiplication x * y is stored in res, which holds the area value.
Table of Content
Using lamda function
A lambda function provides a quick and concise way to compute the area of a rectangle in a single line. It is often used in cases where you need an inline solution, especially when working with functional programming concepts like map() or reduce().
x = 5
y = 8
area = (lambda length, width: length * width)(x, y)
print(area)
Output
40
Explanation: It multiplies x = 5 and y = 8 in a single line area = (lambda length, width: length * width)(x, y) and the result 40, is stored in area.
Using numpy
NumPy is a powerful library for numerical computations, but using it to find the area of a single rectangle is overkill. It is more suitable when dealing with arrays of lengths and widths. This approach is only recommended when performing bulk calculations involving multiple rectangles.
import numpy as np
x = np.array(5) # length
y = np.array(8) # width
area = np.multiply(x, y)
print(area)
Output
40
Explanation np.multiply(x, y) performs element-wise multiplication of x and y using NumPy's multiply() function and stores the result (area) in the variable area.