Shiklo Tools
PDF40
Image20
Calculators & Converters25
Text & Writing13
Developer26
Video14
Audio14
Document14
Data & Spreadsheet12
Web & SEO9
OCR & Scanning5
Archive & File12
Security & Privacy23
Health & Medical29
QR & Barcode5

Python Math

Python is an excellent calculator. Some maths functions are built in and always available; many more are in the math module from the standard library. Together they cover everything from rounding prices to trigonometry for games and science.

Built-in maths functions

print(abs(-7.5))
print(round(2.71828, 2))
print(min(4, 9, 1), max([4, 9, 1]))
print(sum([10, 20, 30]))
print(pow(2, 10), pow(2, 10, 1000))
print(divmod(17, 5))
Output
7.5
2.72
1 9
60
1024 24
(3, 2)

pow with a third argument works out the remainder of a power without computing the huge number first, which is used in cryptography. divmod gives the result of integer division and the remainder together, as a tuple.

The math module

import math

print(math.sqrt(81), math.isqrt(90))
print(math.floor(4.7), math.ceil(4.2), math.trunc(-4.7))
print(math.pi, math.e)
print(math.factorial(6), math.gcd(48, 36), math.lcm(4, 6))
print(round(math.log10(1000)), round(math.log(math.e)), math.log2(8))
Output
9.0 9
4 5 -4
3.141592653589793 2.718281828459045
720 12 12
3 1 3.0

floor rounds down and ceil rounds up to a whole number; trunc simply cuts off the decimals, which for negative numbers is not the same as rounding down. isqrt gives the whole-number part of a square root.

Trigonometry

The trigonometric functions use radians, not degrees. math.radians and math.degrees convert between them:

import math

angle = math.radians(30)
print(round(math.sin(angle), 4), round(math.cos(angle), 4))
print(round(math.degrees(math.atan2(1, 1)), 1))
print(round(math.hypot(3, 4), 1))
Output
0.5 0.866
45.0
5.0

hypot gives the length of the hypotenuse of a right-angled triangle, or the distance of a point from the origin.

Comparing floats

Because floats are stored in binary, results such as 0.1 + 0.2 are not exactly 0.3. Compare floats with math.isclose(a, b) instead of ==, and use math.inf for "infinitely large", for example as a starting value when looking for a minimum.

Practice exercises

  1. Ask for the radius of a circle and print its area and circumference, rounded to 2 decimals.
  2. Print how many full boxes of 12 are needed for 100 eggs with math.ceil.
  3. Work out the distance between the points (1, 2) and (4, 6) with math.hypot.
  4. Check with math.isclose that 0.1 + 0.2 is close to 0.3.