ByteBoard Notes Notes

Use the math module to find the area and circumference of a circle, a hypotenuse, and the ceiling and floor of a number

Computer Science XI · Experiment 26 of 27 · Python

11-CSPython programs
Expt. No.26
Page No.52

math module

Aim

To write a Python program that uses the math module (pi, sqrt(), pow(), ceil(), floor()) to solve small problems.

Concepts used

Algorithm

  1. Import the math module.
  2. Input the radius; display area = pi × r² and circumference = 2 × pi × r.
  3. Input the base and height of a right triangle; display the hypotenuse = √(base² + height²).
  4. Input a decimal number; display its ceiling and floor.

Program

# Using the math module import math r = float(input("Enter the radius of the circle: "))print("Area of the circle  :", round(math.pi * r * r, 2))print("Circumference       :", round(2 * math.pi * r, 2)) a = float(input("Enter the base of a right triangle  : "))b = float(input("Enter the height of a right triangle: "))print("Hypotenuse          :", math.sqrt(math.pow(a, 2) + math.pow(b, 2))) x = float(input("Enter a decimal number: "))print("Ceiling of", x, ":", math.ceil(x))print("Floor of", x, "  :", math.floor(x))

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

Output

$ python math_module.py
Enter the radius of the circle: 7 Area of the circle : 153.94 Circumference : 43.98 Enter the base of a right triangle : 3 Enter the height of a right triangle: 4 Hypotenuse : 5.0 Enter a decimal number: 4.3 Ceiling of 4.3 : 5 Floor of 4.3 : 4

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

Result

For radius 7 the area was 153.94 and the circumference 43.98. The hypotenuse of a 3-4 triangle was 5.0. The ceiling of 4.3 was 5 and its floor 4.

Viva voce: what the examiner may ask

01What is the difference between import math and from math import sqrt?

With import math you write math.sqrt(); with from math import sqrt you can write sqrt() directly.

02What do ceil() and floor() return for -4.3?

ceil(-4.3) is -4 and floor(-4.3) is -5: ceil rounds up and floor rounds down.

03What type does math.pow() return?

Always a float, e.g. math.pow(3, 2) is 9.0.

Variations for the lab test

  1. Find the area of a triangle with Heron's formula using sqrt().
  2. Display sin, cos and tan of 30° (convert to radians first).
  3. Display the value of math.e.
! Common mistake Writing pi without math. after import math raises NameError: name 'pi' is not defined.
Back to the 11-CS index