livepython.net
CHAPTER 18Python Modules
18.2  MATH

Python math Module: sqrt, pi, ceil and floor

Square Root and Pi: math.sqrt() and math.pi

The math module holds maths tools that plain Python doesn't have. Two you'll use most: math.sqrt() finds a square root, and math.pi is the number pi.

PYTHONedit me
import math

print(math.sqrt(144))
print(math.sqrt(2))
print(math.pi)
OUTPUT
12.0
1.4142135623730951
3.141592653589793

Think of it like the special keys on a calculator. A cheap calculator has + and -. A school calculator adds a √ key and a π key. import math turns Python into the school calculator.

The rules

  • math.sqrt(x) gives back the square root of x as a float: math.sqrt(144) is 12.0, not 12.
  • math.pi is a value, not a function: no brackets. It's pi to 15 decimal places.
  • math.e is another such value, the number e (about 2.718), used in science and money maths.
  • Show a long float neatly with :.2f in an f-string, as in chapter 5.

Area of a circle

The area of a circle is pi times the radius squared:

PYTHONedit me
import math

radius = 5
area = math.pi * radius ** 2
print(f"Area: {area:.2f}")
OUTPUT
Area: 78.54

Avoid: brackets after pi

PYTHONedit me
import math

print(math.pi())
OUTPUT
TypeError: 'float' object is not callable

"Not callable" means "you can't put () after it". math.pi is a float, like 3.14, and you can't call a number. Write math.pi.

Avoid: the square root of a negative number

PYTHONedit me
import math

print(math.sqrt(-9))
OUTPUT
ValueError: expected a nonnegative input, got -9.0

No real number times itself gives -9, so sqrt() refuses. "Nonnegative" means zero or more. Check the number with if first, or catch the ValueError with try/except from chapter 17.

Common beginner doubt: "Can't I write x ** 0.5 instead?" Yes, that's also a square root! But math.sqrt(x) says what it does, so it's easier to read.

math.sqrt(x) gives a float square root; math.pi is a value, so it has no brackets.

your turnPredict the output

What will this print?

import math print(math.sqrt(16) + 1)
Your turn! What will this code show on the screen?
your turnSpot the bug

Which line breaks?

One line stops this program. Tap it.

math.ceil() and math.floor(): Round Up and Round Down

math.ceil() rounds a number up to the next whole number, and math.floor() rounds it down. Both give back an int.

PYTHONedit me
import math

print(math.ceil(4.1))
print(math.floor(4.9))
print(math.ceil(7))
OUTPUT
5
4
7

Think of it like a building. The ceiling is above you, so ceil() goes up. The floor is below you, so floor() goes down. A number that is already whole, like 7, stays where it is.

Four ways to make a whole number

Code4.5 becomes-4.5 becomesWhat it does
math.ceil(x)5-4always up
math.floor(x)4-5always down
int(x)4-4cuts off the decimals
round(x)4-4to the nearest; a .5 goes to the even number

Look at the negative column: up means toward zero, so ceil(-4.5) is -4. And floor() is not the same as int() for negative numbers.

A real job for ceil(): how many buses?

52 students go on a trip, and a bus has 40 seats. 52 / 40 is 1.3, but you can't book 1.3 buses. Any part of a bus means a whole extra bus:

PYTHONedit me
import math

students = 52
seats = 40
buses = math.ceil(students / seats)
print("Buses needed:", buses)
OUTPUT
Buses needed: 2

Common mistake: // for "how many do I need?"

// from chapter 5 rounds down, like floor(). It answers "how many full buses?", which is 1. Then 12 students stay at school! When a leftover part still needs a whole one, use ceil().

Common beginner doubt: "Why not round()?" round(1.3) is 1 too. Rounding to the nearest is great for showing prices, but wrong for counting what you need.

ceil() always rounds up, floor() always rounds down. Use ceil() when a leftover part needs a whole one.

your turnPick the right idea

A box holds 6 eggs. Which line finds how many boxes 20 eggs need?

Think about it, then pick one.
your turnFix the code

Fix the code so it prints how many pages 45 photos need, 10 photos per page: 5

It should print: 5

import math

photos = 45
per_page = 10
print(math.floor(photos / per_page))
This code does not work yet. Fix it, then press Run.

math.pow() vs **, math.fabs() and Other math Functions

Some math functions look like things Python can already do. The difference is the type they give back: math.pow() and math.fabs() always give back a float.

PYTHONedit me
import math

print(2 ** 3)
print(math.pow(2, 3))
print(abs(-7))
print(math.fabs(-7))
OUTPUT
8
8.0
7
7.0

Think of it like two shops that sell the same apple. One hands it to you as it is; the other always puts it in a bag. Same apple, different wrapping: 8 or 8.0.

Side by side

Plain Pythonmath versionDifference
2 ** 3 gives 8math.pow(2, 3) gives 8.0** keeps an int; pow() always gives a float
abs(-7) gives 7math.fabs(-7) gives 7.0abs() keeps the type; fabs() always gives a float

For everyday code, ** and abs() are shorter and keep whole numbers whole. Use the math versions when you want a float every time.

abs() gives the absolute value: how far a number is from zero, without its minus sign. It's handy for "how far apart are these two numbers?": abs(3 - 10) is 7.

A few more tools in math

FunctionWhat it givesExample
math.factorial(n)1 * 2 * ... * nmath.factorial(5) is 120
math.gcd(a, b)greatest common divisormath.gcd(12, 18) is 6
math.isqrt(n)whole-number square root, rounded downmath.isqrt(20) is 4
PYTHONedit me
import math

print(math.factorial(5))
print(math.isqrt(20))
OUTPUT
120
4

Avoid: a factorial of a negative number

PYTHONedit me
import math

print(math.factorial(-3))
OUTPUT
ValueError: factorial() not defined for negative values

Common beginner doubt: "Do I have to learn every function in math?" No! Remember the ones in this topic. When you need something else, search "python math" and read the list in Python's documentation.

math.pow() and math.fabs() always give a float; ** and abs() keep whole numbers whole.

your turnType the output

Type what this prints

import math print(math.pow(3, 2))
Read the code line by line, then type the output exactly.
your turnPredict the output

Remember round() from chapter 5?

print(round(7.456, 2))
Your turn! What will this code show on the screen?

Geometry with the math Module: Circles and Triangles

Put the math tools inside your own functions from chapter 15, and you get a small geometry kit you can use again and again.

PYTHONedit me
import math

def circle_area(radius):
    return math.pi * radius ** 2

def circumference(radius):
    return 2 * math.pi * radius

print(f"{circle_area(3):.2f}")
print(f"{circumference(3):.2f}")
OUTPUT
28.27
18.85

Think of it like a set of cookie cutters. You make each shape once, and then you can press out as many cookies as you like.

Formulas you'll use

ShapeFormulaIn Python
circle areapi times r squaredmath.pi * r ** 2
circle edge (circumference)2 times pi times r2 * math.pi * r
long side of a right trianglesquare root of a squared plus b squaredmath.sqrt(a ** 2 + b ** 2)
  • import math goes once, at the top: every function below can use it.
  • Keep the full float inside the function. Round only when you print, with :.2f.

The long side of a right triangle

A ladder stands 4 metres from a wall and reaches 3 metres up. How long is it? This is Pythagoras: the long side (the hypotenuse) is the square root of a ** 2 + b ** 2.

PYTHONedit me
import math

def hypotenuse(a, b):
    return math.sqrt(a ** 2 + b ** 2)

print(hypotenuse(3, 4))
print(f"{hypotenuse(1, 1):.3f}")
OUTPUT
5.0
1.414

Distance between two points

The same idea measures the straight line between two points on a map, (x1, y1) and (x2, y2): how far apart they are across, and how far up and down.

PYTHONedit me
import math

x1, y1 = 1, 2
x2, y2 = 4, 6
distance = math.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2)
print("Distance:", distance)
OUTPUT
Distance: 5.0

Common mistake: math.sqrt(a ** 2) + b ** 2. The brackets end too early, so only a ** 2 is inside the square root. Put the whole sum inside: math.sqrt(a ** 2 + b ** 2).

Wrap math formulas in your own functions; keep full floats inside and round only when you print.

your turnOrder the lines

A square has an area of 36. Put the lines in order to print its diagonal

  1. diagonal = math.sqrt(side ** 2 + side ** 2)
  2. import math
  3. print(f"{diagonal:.2f}")
  4. side = math.sqrt(36)
These lines are mixed up. Put them back in order, then press Check.
your turnPick the right idea

Sunny's code prints 19.0 for the hypotenuse of a 3 by 4 triangle: math.sqrt(a ** 2) + b ** 2. What's wrong?

Think about it, then pick one.

Practice: math

Solve these to lock in what you learned in this topic. Each one runs in your browser.

  1. 162.Python Program to Find the Area and Circumference of a CircleEasySolve
  2. 163.Python Program to Find How Many Boxes You Need Using math.ceilEasySolve
  3. 164.Python Program to Find the Distance Between Two PointsMediumSolve