Skip to Content
Nextra 4.0 is released 🎉

math

The math library gives you access to common math operations that Python doesn’t have built-in.

import math

Common Functions

math.sqrt() — Square Root

math.sqrt(25) # 5.0 math.sqrt(2) # 1.4142135623730951

math.floor() and math.ceil() — Rounding

floor() rounds down, ceil() rounds up.

math.floor(4.9) # 4 math.ceil(4.1) # 5

math.abs() — Absolute Value

Actually, absolute value is just a built-in — use abs() without importing math:

abs(-7) # 7 abs(3) # 3

math.pow() — Exponents

math.pow(2, 8) # 256.0

You can also use the ** operator for the same thing:

2 ** 8 # 256

Constants

math also includes a few useful constants:

math.pi # 3.141592653589793 math.e # 2.718281828459045 math.inf # infinity

math functions usually return a float (a decimal number), even if the result is a whole number. math.sqrt(25) gives 5.0, not 5. Use int() to convert if needed.

Try it out

main.py
Output
Last updated on