math
The math library gives you access to common math operations that Python doesn’t have built-in.
import mathCommon Functions
math.sqrt() — Square Root
math.sqrt(25) # 5.0
math.sqrt(2) # 1.4142135623730951math.floor() and math.ceil() — Rounding
floor() rounds down, ceil() rounds up.
math.floor(4.9) # 4
math.ceil(4.1) # 5math.abs() — Absolute Value
Actually, absolute value is just a built-in — use abs() without importing math:
abs(-7) # 7
abs(3) # 3math.pow() — Exponents
math.pow(2, 8) # 256.0You can also use the ** operator for the same thing:
2 ** 8 # 256Constants
math also includes a few useful constants:
math.pi # 3.141592653589793
math.e # 2.718281828459045
math.inf # infinitymath 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