Python Programming from First Principles: Learn to Code, Think Computationally, and Solve Real-World Problems
PDFEPUB
BOOK 000 · CHAPTER 6 · The`math` Module

The math Module

On this pageMathematical ConstantsPower and RootsLogarithmic FunctionsRounding Functions:floor(),ceil()Trigonometric Functions:sin(),cos(),tan()Factorials, Combinations, and PermutationsRounding to Whole Numbers

Mathematics is a crucial part of many programming tasks — from simple calculations to advanced data analysis.

Python’s math module provides access to mathematical functions that go beyond basic arithmetic.

It includes constants, power and logarithmic functions, trigonometry, and rounding tools that make it easier to perform scientific and statistical computations.

To use any of these functions, you must first import the module:

import math
Listing 247 — The math Module

Mathematical Constants

The math module includes useful constants like π (pi) and e (Euler’s number), which are widely used in geometry, physics, and probability.

print("Pi constant:", math.pi)
print("Euler’s number:", math.e)
Listing 248 — Mathematical Constants

Output

Pi constant: 3.141592653589793
Euler’s number: 2.718281828459045

You can use these constants to compute values like the circumference of a circle:

radius = 5
circumference = 2 * math.pi * radius
print("Circumference of the circle:", circumference)
Listing 249 — Mathematical Constants

Output

Circumference of the circle: 31.41592653589793

Power and Roots

The math module provides functions for exponentiation and square roots. math.pow() converts its arguments to floats; integer exponentiation with ** can retain exact integer results.

print("Square root of 25:", math.sqrt(25))
print("2 raised to the power of 5:", math.pow(2, 5))
print("Exponential of 2:", math.exp(2))
Listing 250 — Power and Roots

Output

Square root of 25: 5.0
2 raised to the power of 5: 32.0
Exponential of 2: 7.38905609893065

Here:

  • sqrt(x) computes √x
  • pow(x, y) returns x raised to y
  • exp(x) returns eˣ These are fundamental in fields like data science and finance where growth rates and probabilities are calculated.

Logarithmic Functions

Logarithms are used to measure growth, decay, and changes in scale, such as population growth, sound intensity, or pH levels in chemistry. The math module provides several logarithmic functions for different bases:

  • math.log(x) returns the natural logarithm (base e), where e is a special mathematical constant approximately equal to 2.718, often used to describe continuous growth or decay.
  • math.log10(x) returns the base-10 logarithm, commonly used in engineering and scientific scales.
  • math.log2(x) returns the base-2 logarithm, often used in computer science for binary calculations.

For example:

print("Natural log of e:", math.log(math.e))
print("Log base 10 of 1000:", math.log10(1000))
print("Log base 2 of 8:", math.log2(8))
Listing 251 — Logarithmic Functions

Output

Natural log of e: 1.0
Log base 10 of 1000: 3.0
Log base 2 of 8: 3.0

Here:

  • math.log(10) means ln(10), or the power you raise e to get 10.
  • math.log10(1000) equals 3 because 10³ = 1000.
  • math.log2(8) equals 3 because 2³ = 8.

Logarithms appear everywhere — from analyzing exponential growth to compressing data ranges in visualizations.

These are essential when working with sound frequencies, exponential growth models, and data transformations.

Rounding Functions:floor(),ceil()

The math module includes precise rounding functions that control how numbers are approximated.

print("Floor of 3.7:", math.floor(3.7))   # Rounds down
print("Ceil of 3.2:", math.ceil(3.2))     # Rounds up
print("Absolute value of -5.3:", math.fabs(-5.3))
Listing 252 — Rounding Functions: floor() , ceil()

Output

Floor of 3.7: 3
Ceil of 3.2: 4
Absolute value of -5.3: 5.3

Use floor to count complete units and ceil to find the number of containers needed. Monetary rounding requires its own explicit rules.

Trigonometric Functions:sin(),cos(),tan()

The math module includes trigonometric functions such as sin(),cos(), and tan().

These functions expect angles in radians, not degrees, and are used to calculate the sine, cosine, and tangent of an angle.

import math

angle = math.pi / 4  # 45 degrees in radians

print("Sine:", math.sin(angle))
print("Cosine:", math.cos(angle))
print("Tangent:", math.tan(angle))
Listing 253 — Trigonometric Functions: sin() , cos() , tan()

Output

Sine: 0.7071067811865475
Cosine: 0.7071067811865476
Tangent: 0.9999999999999999

Here:

  • math.sin(x) returns the sine of the angle x.
  • math.cos(x) returns the cosine of the angle x.
  • math.tan(x) returns the tangent of the angle x.

These functions are used in geometry, physics, and computer graphics where angles and rotations need to be measured precisely.

Since trigonometric functions use radians, you can convert degrees to radians using math.radians():

degrees = 90
radians = math.radians(degrees)
print(f"{degrees}° in radians is:", radians)
Listing 254 — Trigonometric Functions: sin() , cos() , tan()

Output

90° in radians is: 1.5707963267948966

And to convert back from radians to degrees, use math.degrees():

print("Radians to degrees:", math.degrees(math.pi))
Listing 255 — Trigonometric Functions: sin() , cos() , tan()

Output

Radians to degrees: 180.0

Factorials, Combinations, and Permutations

The math module also includes tools for counting and probability, which are very common in statistics and combinatorics.

  • math.factorial(n) returns the factorial of a number, which is the product of all positive integers up to n.
  • math.comb(n, k) returns the number of ways to choose k items from n items (without regard to order).
  • math.perm(n, k) returns the number of ways to arrange k items from n items (where order matters).

Let’s see these in action:

import math

print("Factorial of 5:", math.factorial(5))
print("Combinations of 5 choose 2:", math.comb(5, 2))
print("Permutations of 5 choose 2:", math.perm(5, 2))
Listing 256 — Factorials, Combinations, and Permutations

Output

Factorial of 5: 120
Combinations of 5 choose 2: 10
Permutations of 5 choose 2: 20

Here:

  • factorial(5) gives 5 × 4 × 3 × 2 × 1 = 120
  • comb(5, 2) counts how many ways we can pick 2 items from 5, giving 10
  • perm(5, 2) counts how many ways we can arrange 2 items from 5, giving 20

These functions are useful in fields like probability, statistics, and game design, where you need to count possible outcomes or arrangements.

Rounding to Whole Numbers

Sometimes you only need the integer part of a number.

The function math.trunc() removes everything after the decimal point — it cuts off the fractional part instead of rounding up or down.

print("Truncate 7.9:", math.trunc(7.9))
print("Truncate -3.2:", math.trunc(-3.2))
Listing 257 — Rounding to Whole Numbers

Output

Truncate 7.9: 7
Truncate -3.2: -3

Unlike math.floor() or math.ceil(), which round down or up,

math.trunc() simply drops the decimal part and keeps the integer portion.