Python Math


Python has a built-in mathematical functions, including a comprehensive mathematical module, that allows you to perform numerical operations with numbers.


Built-in Math Functions

The min() and max() functions can be used to determine the lowest or highest value in iterable:


Example
x = min(5, 10, 25)
y = max(5, 10, 25)

print(x)
print(y)

The abs() function returns the total (positive) value of the specified number:


Example
x = abs(-7.25)

print(x)

The pow(x, y) function returns the value of x to the power of y (xy).


Example
x = pow(4, 3)

print(x)


The Math Module

Python also has a built-in module called math, which expands the list of mathematical functions.

To use it, you must enter a math module:


import math

Once you have entered the math module, you can start using module methods and constants.

The math.sqrt() method, for example, returns the square root of a number:


Example
import math

x = math.sqrt(64)

print(x)

The math.ceil() method rotates the number upwards to the nearest number, and the math.floor() method rotates the number downwards to the nearest number, and returns the result:


Example
import math

x = math.ceil(1.4)
y = math.floor(1.4)

print(x) # returns 2
print(y) # returns 1

math.pi constant, returns the PI value (3.14 ...):


Example
import math

x = math.pi

print(x)