Python Program to Find the Area of a Rectangle

The area of a rectangle in Python is length * width. That’s the whole calculation, and here it is as a program you can run:

length = 12
width = 5
print("Area:", length * width)          # 60

What people usually need on top of that is the version that asks the user for the numbers, and one that survives being given nonsense. Both are below.

Each program on this page was run on Python 3.12.5, and the screenshots are those runs.

Python program to find the area of a rectangle

Start with fixed values so you can check the answer by hand. Perimeter costs one more line, and it’s almost always the next thing asked for:

length = 12
width = 5

area = length * width

print("Length   :", length)
print("Width    :", width)
print("Area     :", area)
print("Perimeter:", 2 * (length + width))

Output:

Length   : 12
Width    : 5
Area     : 60
Perimeter: 34
Command Prompt showing a Python program printing the length, width, area and perimeter of a rectangle
12 by 5 gives an area of 60 and a perimeter of 34.

Area multiplies the two sides; perimeter adds them and doubles the result. Keep both in the same program and you’ve answered the usual follow-up before it arrives.

How do you take the rectangle sides as input?

This is the version most assignments ask for. input() always hands back a string, so it has to be converted before any arithmetic:

length = float(input("Enter the length of the rectangle: "))
width = float(input("Enter the width of the rectangle: "))

area = length * width
perimeter = 2 * (length + width)

print(f"Area      = {area:.2f}")
print(f"Perimeter = {perimeter:.2f}")

Run with 12.5 and 4 typed in:

Enter the length of the rectangle: Enter the width of the rectangle: Area      = 50.00
Perimeter = 33.00
Command Prompt showing a Python program asking for the length and width of a rectangle and printing the area and perimeter
The prompts, the typed values, and the result formatted to two decimals.

Use float() rather than int() unless you’re certain the sides are whole numbers. A wall measured at 12.5 metres is perfectly ordinary and int() would reject it.

f"{area:.2f}" rounds the display to two decimal places without changing the stored value.

The rectangle area as a reusable function

Once the calculation lives in a function you can call it as often as you like, and you get somewhere sensible to put the checks:

def rectangle_area(length, width):
    """Return the area of a rectangle."""
    if length <= 0 or width <= 0:
        raise ValueError("length and width must be positive")
    return length * width


print(rectangle_area(12, 5))
print(rectangle_area(2.5, 4))

try:
    rectangle_area(-3, 5)
except ValueError as error:
    print("ValueError:", error)

Output:

60
10.0
ValueError: length and width must be positive

Raising ValueError on a negative side is the right move. A rectangle with a side of -3 isn’t a rectangle, and returning a negative area would hide the mistake, much like any other range check you skip.

Validating the length and width

Real input is messy. This loop keeps asking until it gets a positive number, handling both letters and negatives:

def read_positive(prompt):
    """Keep asking until the person types a positive number."""
    while True:
        try:
            value = float(input(prompt))
        except ValueError:
            print("  that is not a number, try again")
            continue
        if value <= 0:
            print("  the value must be greater than zero")
            continue
        return value


length = read_positive("Length: ")
width = read_positive("Width: ")
print(f"Area = {length * width:.2f}")

Typing abc, then -4, then two good values:

Length:   that is not a number, try again
Length:   the value must be greater than zero
Length: Width: Area = 28.00
Command Prompt showing a Python program rejecting the text abc and a negative number before accepting valid dimensions
Two bad inputs rejected with a message, then the area printed.

try and except ValueError catch the letters; the explicit comparison catches the negative. They’re different failures and both need handling.

A Rectangle class with area and perimeter

If the exercise mentions objects or classes, this is the shape it’s looking for:

class Rectangle:
    def __init__(self, length, width):
        self.length = length
        self.width = width

    def area(self):
        return self.length * self.width

    def perimeter(self):
        return 2 * (self.length + self.width)

    def is_square(self):
        return self.length == self.width


room = Rectangle(12, 5)
print("area     :", room.area())
print("perimeter:", room.perimeter())
print("square?  :", room.is_square())

tile = Rectangle(4, 4)
print("tile is a square:", tile.is_square())
print("tiles needed     :", room.area() / tile.area())

Output:

area     : 60
perimeter: 34
square?  : False
tile is a square: True
tiles needed     : 3.75
Command Prompt showing a Python Rectangle class printing area, perimeter, whether it is a square, and how many tiles fit
One class covers area, perimeter and the square check.

A square is just a rectangle with equal sides, so is_square() is a one-line comparison rather than a separate class.

Area of other shapes in Python

The same pattern covers the shapes usually set alongside this one:

import math

length, width = 12, 5

print(f"rectangle : {length * width}")
print(f"square    : {length ** 2}")
print(f"triangle  : {0.5 * length * width}")
print(f"circle    : {math.pi * (length / 2) ** 2:.2f}")

# the same formula handles a wall with a window cut out of it
wall = 12 * 8
window = 3 * 4
print(f"wall minus window: {wall - window} square units")

Output:

rectangle : 60
square    : 144
triangle  : 30.0
circle    : 113.10
wall minus window: 84 square units
ShapeFormulaPython
Rectanglelength × widthl * w
Squareside²s ** 2
Triangle½ × base × height0.5 * b * h
Circleπr²math.pi * r ** 2

Subtracting one area from another is how you handle a wall with a window in it, or a garden with a pond. For rounding the result cleanly, see rounding to 2 decimal places.

More beginner Python programs on this site:

Frequently asked questions

How do you find the area of a rectangle in Python?

Multiply the two sides: area = length * width. Use float(input(...)) when the numbers come from the user. The arithmetic operators are listed in the Python numeric types reference.

How do I write a program to find the area and perimeter of a rectangle?

Area is length * width and perimeter is 2 * (length + width). Print both from the same program.

Why does my program add the numbers instead of multiplying?

input() returns a string, and "12" * 5 repeats text. Wrap each input in float() or int() first.

Should I use int() or float() for the sides?

float(), unless whole numbers are guaranteed. It accepts 12.5 as well as 12, and the result formats the same way.

How do I round the area to 2 decimal places?

Format it when printing: f"{area:.2f}". That leaves the stored value untouched.

How do I stop negative numbers being accepted?

Check the value before calculating and either raise ValueError or ask again in a loop. A negative side is not a rectangle.

How do I write a Rectangle class?

Store the sides in __init__ and add area() and perimeter() methods. A square is the case where both sides match.