🧮

How to Use Math Module in Python

PythonBeginner

Perform mathematical operations with the math module.

Code Example

Python
import math

# Constants
print(f"π = {math.pi}")
print(f"e = {math.e}")

# Basic operations
print(f"\nSquare root of 16: {math.sqrt(16)}")
print(f"2 to the power of 3: {math.pow(2, 3)}")
print(f"Absolute value of -5: {abs(-5)}")

# Trigonometry
angle = math.pi / 4  # 45 degrees
print(f"\nSin(45°) = {math.sin(angle):.4f}")
print(f"Cos(45°) = {math.cos(angle):.4f}")

# Rounding
print(f"\nCeiling of 4.2: {math.ceil(4.2)}")
print(f"Floor of 4.8: {math.floor(4.8)}")

# Logarithms
print(f"\nln(10) = {math.log(10):.4f}")
print(f"log10(100) = {math.log10(100)}")

Explanation

The math module provides mathematical functions and constants. Import it with "import math" and use math.function_name().

Related Tutorials