Python Math: Essential Functions and Operations for Beginners
Python’s standard math module provides functions and constants for floating-point mathematics, including square roots, logarithms, trigonometry, rounding helpers, and combinatorics.
Import the Module
import mathSquare Roots and Powers
print(math.sqrt(16)) # 4.0
print(math.pow(2, 3)) # 8.0
print(2 ** 3) # 8For ordinary exponentiation, the ** operator is usually simpler. math.pow() converts its arguments to floating point and returns a float.
Rounding Helpers
print(math.ceil(4.2)) # 5
print(math.floor(4.8)) # 4
print(math.trunc(4.8)) # 4Python’s built-in round() serves a different purpose and follows round-to-even behavior for halfway cases:
print(round(2.5)) # 2
print(round(3.5)) # 4Absolute Values
For most numeric types, use the built-in abs():
print(abs(-7)) # 7math.fabs() always returns a float:
print(math.fabs(-7)) # 7.0Useful Constants
print(math.pi)
print(math.e)
print(math.tau)
print(math.inf)Trigonometry
The trigonometric functions use radians:
angle = math.radians(30)
print(math.sin(angle))
print(math.cos(angle))
print(math.tan(angle))Convert back to degrees with:
print(math.degrees(math.pi / 2)) # 90.0Logarithms and Exponentials
print(math.log(math.e)) # 1.0
print(math.log10(1000)) # 3.0
print(math.log2(8)) # 3.0
print(math.exp(1)) # emath.log(x, base) also supports a custom base, though specialized log2() and log10() functions can provide clearer intent.
Factorials and Combinatorics
print(math.factorial(5)) # 120
print(math.comb(5, 2)) # 10
print(math.perm(5, 2)) # 20These operate on non-negative integers under their documented constraints.
GCD and LCM
print(math.gcd(24, 36)) # 12
print(math.lcm(6, 8)) # 24Accurate Floating-Point Summation
For many floating-point values, math.fsum() can be more numerically accurate than the built-in sum():
values = [0.1] * 10
print(math.fsum(values))Distance and Hypotenuse
print(math.hypot(3, 4)) # 5.0
print(math.dist((0, 0), (3, 4))) # 5.0math Is for Real-Valued Mathematics
Most math functions expect real numbers. For complex-number operations, use cmath:
import cmath
print(cmath.sqrt(-1)) # 1jFor vectorized numerical work over arrays, NumPy is usually a better fit than repeatedly calling math functions in Python loops.
Conclusion
The math module covers common real-number mathematics without external dependencies. Use built-in operators such as ** and abs() when they express the operation directly, and reach for math when you need specialized functions, constants, combinatorics, or improved numerical routines.