LearnContact
Lesson 4924 min read

Math Module

Learn how to use Python's built-in math module for constants, roots, powers, rounding, trigonometry, and logarithms.

Introduction

Python's basic arithmetic operators (+, -, *, /) handle everyday calculations, but many programs need more advanced mathematical operations — square roots, rounding rules, trigonometry, logarithms, and well-known constants like pi.

Rather than making you calculate these by hand, Python's built-in math module provides fast, accurate implementations of dozens of mathematical functions. This lesson tours the most useful ones.

What You Will Learn
  • Key constants: math.pi and math.e.
  • How to calculate square roots and powers.
  • Rounding down and up with floor() and ceil().
  • How to calculate a factorial.
  • A brief look at trigonometric functions like sin() and cos().
  • How to use log(), and how to check for infinity and "not a number".

The math Module

The math module is part of Python's standard library. Import it once at the top of your file, then access its functions and constants using the math. prefix.

import math

print(math.sqrt(16))
print(math.pi)
Output
4.0
3.141592653589793

Notice that math.sqrt() always returns a float, even when the result is a whole number — this is standard behavior across most of the module's functions.

Mathematical Constants

The math module defines several well-known constants so you never need to type out their digits manually.

math.pi

The ratio of a circle's circumference to its diameter (≈ 3.14159).

math.e

Euler's number, the base of natural logarithms (≈ 2.71828).

math.inf

Represents positive infinity.

math.tau

Equal to 2 × pi (≈ 6.28318), useful in some geometry formulas.

import math

radius = 5
area = math.pi * radius ** 2
print(f"Area: {area:.2f}")
Output
Area: 78.54

Square Roots and Powers

math.sqrt(x) returns the square root of x. math.pow(x, y) raises x to the power of y, similar to the ** operator, but math.pow() always returns a float.

import math

print(math.sqrt(64))
print(math.pow(2, 10))
print(2 ** 10)
Output
8.0
1024.0
1024

For square roots specifically, math.sqrt(x) and x ** 0.5 give the same numeric result, but math.sqrt() is generally preferred because it is clearer to read and raises a proper error for negative numbers instead of returning a complex number.

import math

x = 81
print(math.sqrt(x))
print(x ** 0.5)

try:
    math.sqrt(-9)
except ValueError as e:
    print("Error:", e)
Output
9.0
9.0
Error: math domain error

Rounding: floor() and ceil()

math.floor(x) rounds down to the nearest whole number, and math.ceil(x) rounds up to the nearest whole number. Both return an integer.

import math

print(math.floor(4.7))
print(math.floor(4.1))
print(math.ceil(4.1))
print(math.ceil(4.7))
Output
4
4
5
5
floor/ceil vs round()

Python's built-in round() rounds to the nearest value (with ties going to the nearest even number), while math.floor() always rounds down and math.ceil() always rounds up, regardless of how close the decimal is.

Factorial

math.factorial(n) calculates n! — the product of all positive integers up to n. It is commonly used in combinatorics and probability calculations.

import math

print(math.factorial(5))   # 5 * 4 * 3 * 2 * 1
print(math.factorial(0))   # 0! is defined as 1
Output
120
1

Trigonometric Functions

The math module includes standard trigonometric functions like sin(), cos(), and tan(). These expect the angle in radians, not degrees, so math.radians() is often used to convert first.

import math

angle_degrees = 90
angle_radians = math.radians(angle_degrees)

print(math.sin(angle_radians))
print(round(math.cos(angle_radians), 10))
Output
1.0
0.0

math.cos(90 degrees) is mathematically 0, but floating-point precision can produce a tiny value like 6.12e-17, which is why the example rounds the result for a clean display.

Logarithms

math.log(x) calculates the natural logarithm (base e) of x by default. You can pass a second argument to use a different base.

import math

print(math.log(math.e))     # natural log of e is 1
print(math.log(100, 10))    # log base 10 of 100
print(math.log2(8))         # log base 2 of 8
print(math.log10(1000))     # log base 10 of 1000
Output
1.0
2.0
3.0
3.0

Special Values: math.inf and math.isnan()

math.inf represents infinity, useful as a starting value when searching for a minimum. math.isnan(x) checks whether a value is NaN ("not a number"), which can appear from certain invalid floating-point operations.

import math

smallest = math.inf
for n in [42, 7, 99, 3]:
    if n < smallest:
        smallest = n
print("Smallest:", smallest)

result = float("nan")
print(math.isnan(result))
print(math.isinf(math.inf))
Output
Smallest: 3
True
True

Common Mistakes

Avoid These Mistakes
  • Passing degrees directly into sin(), cos(), or tan() without converting to radians first.
  • Assuming math.sqrt() works on negative numbers — it raises a ValueError instead.
  • Confusing math.floor()/ceil() with round(), which rounds to the nearest value instead of always down or up.
  • Forgetting that math.pow() always returns a float, unlike the ** operator on two integers.
  • Comparing NaN values with == instead of using math.isnan(), since NaN is never equal to anything, even itself.

Best Practices

  • Use math.sqrt() instead of ** 0.5 for clearer, more error-safe code.
  • Convert degrees to radians with math.radians() before using trig functions.
  • Use math.isnan() and math.isinf() to safely check special float values.
  • Prefer the ** operator for simple integer powers, and math.pow() when you explicitly need a float result.
  • Import only what you need with from math import sqrt, pi if you use just a few functions repeatedly.

Frequently Asked Questions

What is the difference between math.sqrt(x) and x ** 0.5?

Both return the same numeric result for non-negative x, but math.sqrt() is more readable and raises a clear ValueError for negative inputs, while ** 0.5 on a negative number produces a complex number result error in Python.

Does the math module work with complex numbers?

No, the math module only works with real numbers (ints and floats). For complex numbers, Python has a separate cmath module.

Why do trig functions need radians instead of degrees?

Mathematically, trigonometric functions are defined in terms of radians. Use math.radians() to convert a degree value before passing it to sin(), cos(), or tan().

What is the difference between math.floor() and int()?

For positive numbers, they behave the same. For negative numbers, int() truncates toward zero (e.g. int(-4.7) is -4), while math.floor() always rounds toward negative infinity (math.floor(-4.7) is -5).

What is math.isnan() used for?

It safely checks whether a float value is NaN ("not a number"), which can result from invalid operations like 0.0 / 0.0. Comparing NaN with == always returns False, so isnan() is the correct way to check for it.

Key Takeaways

  • The math module provides constants like math.pi and math.e.
  • math.sqrt() and math.pow() handle roots and powers, both returning floats.
  • math.floor() and math.ceil() round down and up respectively.
  • math.factorial() calculates n!, and trig functions expect radians, not degrees.
  • math.log() calculates logarithms, and math.inf / math.isnan() handle special float values.

Summary

The math module extends Python's basic arithmetic with constants, roots, rounding rules, trigonometry, and logarithms, saving you from re-implementing these formulas yourself.

In this lesson, you learned about mathematical constants, square roots and powers, floor and ceiling rounding, factorials, trigonometric functions, logarithms, and special values like infinity and NaN.

Lesson Completed
  • You can use math module constants and functions confidently.
  • You understand the difference between floor(), ceil(), and round().
  • You know how to work with trigonometry, logarithms, and special float values.
  • You are ready to explore Python's random module.
Next Lesson →

Random Module