Python Program to Calculate Area of Rectangle
area = length * width.Examples
How to Think About It
Algorithm
Code
length = float(input("Enter the length of the rectangle: ")) width = float(input("Enter the width of the rectangle: ")) area = length * width print("Area of rectangle is", area)
Dry Run
Let's trace the example where length = 5 and width = 3 through the code
Input length
User enters 5, so length = 5.0
Input width
User enters 3, so width = 3.0
Calculate area
area = length * width = 5.0 * 3.0 = 15.0
Print result
Output: Area of rectangle is 15.0
| Step | Variable | Value |
|---|---|---|
| 1 | length | 5.0 |
| 2 | width | 3.0 |
| 3 | area | 15.0 |
Why This Works
Step 1: Getting inputs
We use input() to get length and width from the user and convert them to numbers with float() so we can do math.
Step 2: Calculating area
The area is found by multiplying length and width using *, which gives the total space inside the rectangle.
Step 3: Showing output
We print the result with print() so the user sees the area value clearly.
Alternative Approaches
def rectangle_area(length, width): return length * width l = float(input("Length: ")) w = float(input("Width: ")) print("Area of rectangle is", rectangle_area(l, w))
length = int(input("Enter length: ")) width = int(input("Enter width: ")) area = length * width print("Area of rectangle is", area)
Complexity: O(1) time, O(1) space
Time Complexity
The program performs a fixed number of operations (input, multiplication, output), so it runs in constant time.
Space Complexity
Only a few variables are stored, so the space used is constant regardless of input size.
Which Approach is Fastest?
All approaches run in constant time and space; using a function adds clarity but no performance difference.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Direct calculation | O(1) | O(1) | Simple quick calculation |
| Function method | O(1) | O(1) | Reusable code and clarity |
| Integer inputs | O(1) | O(1) | When only whole numbers are needed |
float() or int() before calculations.