Python: Math and Statistics

Numerical computation is a fundamental programming skill. Python's standard library provides a full set of tools — from basic math functions to statistical analysis, from precise decimal arithmetic to fraction operations. This lesson teaches you to use the right module for the right scenario.


1. math — Mathematical Functions

PYTHON
import math

# Common constants
print(math.pi)                  # 3.141592653589793
print(math.e)                   # 2.718281828459045

# Rounding
print(math.ceil(3.14))          # 4 (ceiling)
print(math.floor(3.14))         # 3 (floor)

# Powers and logarithms
print(math.pow(2, 10))          # 1024.0 (2 to the 10th)
print(math.sqrt(16))            # 4.0 (square root)
print(math.log(100, 10))        # 2.0 (log base 10)

# Trigonometry
print(math.sin(math.pi / 2))    # 1.0
print(math.cos(0))              # 1.0
print(math.radians(180))        # 3.14159... (degrees to radians)

▶ Example: Distance Calculation (Difficulty ⭐)

PYTHON
import math

def distance(x1, y1, x2, y2):
    """Calculate the distance between two points"""
    return math.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2)

def circle_area(radius):
    """Calculate the area of a circle"""
    return math.pi * radius ** 2

print(f"Distance: {distance(0, 0, 3, 4):.2f}")      # 5.00
print(f"Circle area: {circle_area(5):.2f}")          # 78.54
▶ Try it Yourself

Output:

TEXT 📖 Display only
# Function defined successfully


2. statistics — Statistical Analysis

PYTHON
import statistics

data = [12, 15, 18, 20, 22, 25, 30, 35, 40]

# Central tendency
print(statistics.mean(data))        # 24.11 (mean)
print(statistics.median(data))      # 22 (median)
# print(statistics.mode(data))      # mode (errors if no unique mode)

# Dispersion
print(statistics.stdev(data))       # 9.32 (sample standard deviation)
print(statistics.variance(data))    # 86.86 (sample variance)

▶ Example: Score Analysis (Difficulty ⭐⭐)

PYTHON
import statistics

scores = [85, 92, 78, 90, 88, 76, 95, 82, 89, 73]

print("=== Score Analysis ===")
print(f"Mean: {statistics.mean(scores):.1f}")
print(f"Median: {statistics.median(scores)}")
print(f"Max: {max(scores)}")
print(f"Min: {min(scores)}")
print(f"Std Dev: {statistics.stdev(scores):.2f}")

mean = statistics.mean(scores)
std = statistics.stdev(scores)

print("\n=== Grade Distribution ===")
for score in sorted(scores, reverse=True):
    if score > mean + std:
        level = "Excellent ⭐"
    elif score > mean:
        level = "Good 👍"
    elif score > mean - std:
        level = "Average"
    else:
        level = "Needs Work 💪"
    print(f"  {score:3d} — {level}")
▶ Try it Yourself

Output:

TEXT 📖 Display only
=== Score Analysis ===
\n=== Grade Distribution ===


3. decimal — Precise Decimal Arithmetic

▶ Example: City Temperature Statistics (Difficulty ⭐⭐)

PYTHON
import statistics

temps_beijing = [2, 5, 12, 20, 26, 31, 32, 30, 25, 16, 8, 3]
temps_shanghai = [5, 6, 10, 16, 22, 26, 30, 30, 26, 20, 13, 7]

print("=== City Temperature Statistics ===")
for city, temps in [("Beijing", temps_beijing), ("Shanghai", temps_shanghai)]:
    mean_val = statistics.mean(temps)
    median_val = statistics.median(temps)
    stdev_val = statistics.stdev(temps)
    print(f"\n{city}:")
    print(f"  Annual mean: {mean_val:.1f}C")
    print(f"  Median: {median_val:.1f}C")
    print(f"  Std deviation: {stdev_val:.1f}C")
    print(f"  Range: {mean_val - stdev_val:.1f}C ~ {mean_val + stdev_val:.1f}C")
▶ Try it Yourself

Output:

TEXT 📖 Display only
=== City Temperature Statistics ===

Beijing:
  Annual mean: 17.5C
  Median: 18.0C
  Std deviation: 11.3C
  Range: 6.2C ~ 28.8C

Shanghai:
  Annual mean: 17.6C
  Median: 18.0C
  Std deviation: 9.3C
  Range: 8.2C ~ 26.9C


3. decimal — Precise Decimal Arithmetic

PYTHON
from decimal import Decimal, getcontext

# float precision issue
print(0.1 + 0.2)                    # 0.30000000000000004 ❌

# Decimal precise calculation
print(Decimal("0.1") + Decimal("0.2"))      # 0.3 ✅

# Set precision
getcontext().prec = 4               # Global precision of 4 digits
print(Decimal(1) / Decimal(3))      # 0.3333 (4 digits)

# Financial calculations must use Decimal
price = Decimal("19.99")
quantity = Decimal("3")
tax_rate = Decimal("0.08")
total = price * quantity
tax = total * tax_rate
print(f"Total: {total:.2f}")          # 59.97
print(f"Tax: {tax:.2f}")              # 4.80
print(f"Payable: {total + tax:.2f}")  # 64.77
💡 Always use Decimal for financial calculations, never float. The 0.1 + 0.2 precision issue is fatal in finance. Decimal sacrifices some performance for precise decimal arithmetic.



4. fractions — Fraction Arithmetic

PYTHON
from fractions import Fraction

# Create fractions
f1 = Fraction(1, 3)                 # 1/3
f2 = Fraction(2, 6)                 # Auto-reduces to 1/3
print(f1)                           # 1/3
print(f2)                           # 1/3
print(f1 == f2)                     # True

# Fraction operations
a = Fraction(1, 2)
b = Fraction(1, 3)
print(a + b)                        # 5/6
print(a * b)                        # 1/6
print(a / b)                        # 3/2

# Conversion between fractions and floats
print(float(Fraction(1, 3)))        # 0.3333333333
print(Fraction(0.25).limit_denominator())  # 1/4


5. Common Use Cases


❓ FAQ

Q What's the difference between the math module and built-in abs(), round(), sum()?
A Built-in functions handle basic operations (absolute value, rounding, summation). math provides more specialized functions (trigonometry, logarithms, factorial). Use built-ins when they suffice.
Q Is statistics.mean() any better than manually computing the average?
A mean() is optimized internally (one pass for both sum and count), performs better for large datasets, and handles edge cases like empty lists.
Q When should I use Fraction vs Decimal?
A Use Fraction when you need exact rational arithmetic (like fraction exercises in educational software). Use Decimal for decimal calculations with controlled precision (like finance). For simple cases, float is fine — 99% of daily programming won't need either of these.

📖 Summary


📝 Exercises

  1. Basic (Difficulty ⭐): Use the math module to calculate the area and circumference of a circle with radius 7.

  2. Intermediate (Difficulty ⭐⭐): Given data = [23, 45, 67, 12, 34, 56, 78, 90, 11, 43], use statistics to calculate mean, median, and standard deviation. Then use math to determine which values fall within "mean ± standard deviation."

  3. Challenge (Difficulty ⭐⭐⭐): Write a "shopping cart checkout" program. Products have names, unit prices (Decimal), and quantities. After adding items, calculate the total, tax (8%), and discount (subtract 10 for every 100), then output the final amount. Requirement: All monetary calculations must use Decimal.

Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏