Python Program to Find Area of Rectangle
area = length * width. For example, area = 5 * 3 calculates the area as 15.Examples
How to Think About It
* operator.Algorithm
Code
length = float(input('Enter length of rectangle: ')) width = float(input('Enter width of 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 = 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 as strings, then convert them to numbers with float().
Step 2: Calculating area
We multiply length and width using * to find the area inside the rectangle.
Step 3: Displaying output
We print the result with a clear message so the user understands the output.
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 used to store inputs and the result, so space usage is constant.
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 one-time calculation |
| Function method | O(1) | O(1) | Reusable code and clarity |
| Integer inputs | O(1) | O(1) | When only whole numbers are needed |