Python math Module

The math module in Python provides standard mathematical functions such as square root, factorial, trigonometry, logarithms, rounding, and mathematical constants.

To use the math module, you need to import it:

import math

1. math.sqrt(x) – Square Root

import math
print(math.sqrt(16))

Output:

4.0

Explanation:

The sqrt() function returns the square root of a number. Here, the square root of 16 is 4.0. It always returns a float.

2. math.pow(x, y) – Power

import math
print(math.pow(2, 3))

Output:

8.0

Explanation:
This raises 2 to the power of 3 (2³ = 8). The result is always returned as a float, unlike the ** operator which can return an int if possible.

3. math.factorial(x) – Factorial

import math
print(math.factorial(5))

Output:

120

Explanation:
The factorial of 5 (5!) is 5 × 4 × 3 × 2 × 1 = 120. This function only accepts non-negative integers.

4. math.floor(x) – Round Down

import math
print(math.floor(5.7))

Output:

5

Explanation:
Rounds 5.7 down to the nearest integer less than or equal to 5.7.

5. math.ceil(x) – Round Up

import math
print(math.ceil(5.1))

Output:

6

Explanation:
Rounds 5.1 up to the nearest integer greater than or equal to 5.1.

6. math.pi – Pi Constant

import math
print(math.pi)

Output:

3.141592653589793

Explanation:
This gives the value of π (pi), a mathematical constant useful in geometry and trigonometry.

7. math.e – Euler’s Number

import math
print(math.e)

Output:

2.718281828459045

Explanation:
This returns Euler's number (e), the base of the natural logarithm, important in exponential functions.

8. Trigonometric Functions: math.sin(), math.cos(), math.tan()

import math
print(math.sin(math.pi / 2))

Output:

1.0

Explanation:
Calculates the sine of π/2 radians (90 degrees), which is 1. Trigonometric functions use radians, not degrees.

9. math.log(x, base) – Logarithm

import math
print(math.log(100, 10))

Output:

2.0

Explanation:
Calculates the base-10 logarithm of 100. Since 10² = 100, the result is 2.

10. Convert Between Degrees and Radians

import math
print(math.degrees(math.pi))   # Radians to degrees
print(math.radians(180))       # Degrees to radians

Output:

180.0
3.141592653589793

Explanation:

  • degrees() converts radians to degrees (π ≈ 180°).
  • radians() converts degrees to radians (180° ≈ π radians).

View All Functions and Constants

import math
print(dir(math))

Explanation:
This lists all the functions, classes, and constants available in the math module.

Summary Table of Common math Functions

Function/ConstantDescription
math.sqrt(x)Square root of x
math.pow(x, y)x raised to the power y
math.factorial(x)Factorial of x
math.floor(x)Floor value (round down)
math.ceil(x)Ceiling value (round up)
math.piπ (pi), approx. 3.14159
math.eEuler's number, approx. 2.71828
math.sin(x)Sine of x (x in radians)
math.log(x, base)Logarithm of x to the given base
math.degrees(x)Convert x radians to degrees
math.radians(x)Convert x degrees to radians