Python Math
Python includes built-in mathematical functions like min(), max(), abs(), pow(), and round(), along with a dedicated math module for square roots, rounding up/down, trigonometry, and constants like math.pi.
1. Built-in Math Functions
You can use these functions directly without importing any extra module:
numbers = [14, 5, 29, 8, 42]
print("Min:", min(numbers)) # Output: 5
print("Max:", max(numbers)) # Output: 42
print("Absolute:", abs(-19.5)) # Output: 19.5
print("Power (2^5):", pow(2, 5)) # Output: 32
print("Rounded:", round(3.14159, 2)) # Output: 3.14
2. Using the math Module
Import the math module to access functions such as sqrt(), ceil(), and floor():
import math
print("Square root of 81:", math.sqrt(81)) # Output: 9.0
print("Ceil of 4.2:", math.ceil(4.2)) # Output: 5 (rounds up)
print("Floor of 4.8:", math.floor(4.8)) # Output: 4 (rounds down)
3. Mathematical Constants (math.pi)
The math module also provides useful constants such as math.pi and math.e:
import math
radius = 7
area = math.pi * (radius ** 2)
print("Pi value:", math.pi)
print("Circle Area:", round(area, 2))
Tip:
math.ceil() always rounds a float up to the next integer, whereas math.floor() always rounds it down to the nearest integer.