ByteBoard Notes Notes

To calculate the perimeter or circumference and area of a triangle, rectangle, square and circle

Informatics Practices XI · Experiment 03 of 36 · Python

★ CBSE suggested11-IPPython programs
Expt. No.03
Page No.6

Perimeter and area of shapes

Aim

To write a menu-driven Python program that calculates the perimeter (or circumference) and area of a triangle, a rectangle, a square or a circle.

Concepts used

Algorithm

  1. Display a menu of four shapes and input the choice.
  2. Triangle: input three sides; perimeter = a + b + c; area by Heron's formula with s = perimeter ÷ 2.
  3. Rectangle: perimeter = 2 × (l + b), area = l × b.
  4. Square: perimeter = 4 × side, area = side × side.
  5. Circle: circumference = 2 × 3.14 × r, area = 3.14 × r × r.

Program

# Perimeter and area of shapes print("1. Triangle  2. Rectangle  3. Square  4. Circle")choice = int(input("Enter your choice: "))if choice == 1:    a = float(input("Side a: "))    b = float(input("Side b: "))    c = float(input("Side c: "))    s = (a + b + c) / 2    area = (s * (s - a) * (s - b) * (s - c)) ** 0.5    print("Perimeter:", a + b + c, " Area:", area)elif choice == 2:    l = float(input("Length : "))    b = float(input("Breadth: "))    print("Perimeter:", 2 * (l + b), " Area:", l * b)elif choice == 3:    side = float(input("Side: "))    print("Perimeter:", 4 * side, " Area:", side * side)elif choice == 4:    r = float(input("Radius: "))    print("Circumference:", 2 * 3.14 * r, " Area:", 3.14 * r * r)else:    print("Invalid choice")

A marked line continues the line above it. In your file, write it on the same line.

Output

Run 1
$ python perimeter_area_shapes.py
1. Triangle 2. Rectangle 3. Square 4. Circle Enter your choice: 1 Side a: 3 Side b: 4 Side c: 5 Perimeter: 12.0 Area: 6.0
Run 2
$ python perimeter_area_shapes.py
1. Triangle 2. Rectangle 3. Square 4. Circle Enter your choice: 4 Radius: 7 Circumference: 43.96 Area: 153.86

✓ Printed by running this program, not typed by hand.

Result

For the 3-4-5 triangle the perimeter was 12.0 and the area 6.0. For a circle of radius 7 the circumference was 43.96 and the area 153.86 (using π = 3.14).

Viva voce: what the examiner may ask

01How is a square root found without the math module?

By raising to the power 0.5: x ** 0.5.

02What is Heron's formula?

Area = √(s(s−a)(s−b)(s−c)), where s is half the perimeter.

03Why does the circle area differ slightly from 153.94?

3.14 is only an approximation of π; using 22/7 or a more exact value gives a slightly different answer.

Variations for the lab test

  1. Add a choice for a parallelogram.
  2. Check that the three sides can form a triangle before finding its area.
  3. Repeat the menu until the user chooses Exit.
! Common mistake Writing s * (s - a) * (s - b) * (s - c) 0.5 takes the root of only the last bracket, because has higher precedence than *.
Back to the 11-IP index