Math

The Math Module

The math module in Python provides access to a wide range of mathematical functions and constants. It's extremely useful when working with more advanced numerical calculations beyond basic arithmetic. Before using any functions from the module, you need to import it at the top of your script:

import math

Then you can access the functions and constants. Some of the most useful are:

Function or Constant Description
math.pi The value of π (3.14159...)
math.e The value of Euler's number (≈2.718)
math.sqrt(x) Returns the square root of x
math.pow(x, y) Returns x raised to the power y
math.floor(x) Rounds down to the nearest whole number
math.ceil(x) Rounds up to the nearest whole number
math.trunc(x) Truncates decimal (just keeps the integer part)
math.fabs(x) Returns the absolute value (always positive)
math.factorial(x) Returns the factorial of x
math.log(x) Returns natural logarithm (base e)
math.log10(x) Logarithm base 10
math.sin(x) / math.cos(x) / math.tan(x) Trigonometric functions (input in radians)
math.degrees(x) Converts radians to degrees
math.radians(x) Converts degrees to radians
math.isclose(a, b) Checks if two numbers are close in value
math.gcd(a, b) Finds the greatest common divisor of a and b

The Statistics Module

The statistics module is another helpful library for simple data analysis. It's built into Python and offers methods to calculate averages and other statistical properties.

import statistics

data = [10, 15, 20, 25, 30]
print(statistics.mean(data))     # Average (mean)
print(statistics.median(data))   # Middle value
print(statistics.mode(data))     # Most common value
print(statistics.stdev(data))    # Standard deviation

The Random Module

The random module is perfect for generating random numbers, selecting random items, and even shuffling data.

import random

Function Description
random.randint(a, b) Returns a random integer between a and b (inclusive)
random.randrange(n) Returns a random integer from 0 up to (but not including) n
random.random() Returns a random float between 0.0 and 1.0
random.choice(sequence) Picks a random element from a list, tuple, or string
random.shuffle(list) Randomly shuffles the elements of a list (in-place)
random.uniform(a, b) Returns a random float between a and b