Math and Statistics Examples
Short, runnable programs that show python math and statistics in action. Read the explanation, press Run, then change the code and try your own ideas. New to the topic? Start with the Python math and statistics lesson.
1Pages, boxes and clock time with ceil and divmod
ceil answers "how many containers do I need?" because it never rounds a partial page down. divmod splits a total into whole units and a remainder.
import math
items = 47
per_page = 10
pages = math.ceil(items / per_page)
print(items, "items need", pages, "pages")
print("Rounded down you would lose", items - (items // per_page) * per_page, "items")
seconds = 3725
minutes, secs = divmod(seconds, 60)
hours, minutes = divmod(minutes, 60)
print(f"{hours:02d}:{minutes:02d}:{secs:02d}")Expected output47 items need 5 pages
Rounded down you would lose 7 items
01:02:05
2Distance between two points
hypot gives the straight-line distance from the differences in x and y. atan2 then finds the direction, and degrees converts it from radians.
import math
shop = (2, 3)
customer = (8, 11)
dx = customer[0] - shop[0]
dy = customer[1] - shop[1]
distance = math.hypot(dx, dy)
angle = math.degrees(math.atan2(dy, dx))
print("Distance:", distance)
print("Direction:", round(angle, 1), "degrees from the x-axis")Expected outputDistance: 10.0
Direction: 53.1 degrees from the x-axis
3Teams, podiums and timetables with comb, perm and lcm
Use comb when the order of the chosen items does not matter (a team) and perm when it does (a podium). factorial counts line-ups, and lcm and gcd answer timetable questions.
import math
players = 12
print("Teams of 5:", math.comb(players, 5))
print("Gold, silver, bronze:", math.perm(players, 3))
print("Seating 6 guests in a row:", math.factorial(6))
bus_a = 12
bus_b = 18
print("Both buses meet again after", math.lcm(bus_a, bus_b), "minutes")
print("Largest shared timetable step:", math.gcd(bus_a, bus_b), "minutes")Expected outputTeams of 5: 792
Gold, silver, bronze: 1320
Seating 6 guests in a row: 720
Both buses meet again after 36 minutes
Largest shared timetable step: 6 minutes
4How long until savings double?
Growth of 5% a year is a multiplication by 1.05 every year, so the number of years is a logarithm: log(2) / log(1.05). Rounding up with ceil gives whole years.
import math
rate = 0.05
years = math.log(2) / math.log(1 + rate)
print("Years to double:", round(years, 2))
print("In whole years:", math.ceil(years))
balance = 1000 * (1 + rate) ** math.ceil(years)
print("Balance then:", round(balance, 2))Expected outputYears to double: 14.21
In whole years: 15
Balance then: 2078.93
5Mean versus median with an outlier
One unusually large order drags the mean far above a typical order, while the median stays put. quantiles shows the spread of the middle of the data.
import statistics
orders = [18, 22, 19, 25, 21, 20, 24, 240]
print("Mean:", statistics.mean(orders))
print("Median:", statistics.median(orders))
print("Quartiles:", statistics.quantiles(orders, n=4))
typical = [o for o in orders if o < 100]
print("Mean without the outlier:", round(statistics.mean(typical), 2))Expected outputMean: 48.625
Median: 21.5
Quartiles: [19.25, 21.5, 24.75]
Mean without the outlier: 21.29
6Exact money with Decimal and exact recipes with Fraction
Decimal adds prices without float noise and quantize rounds to cents the way a shop does. Fraction scales a recipe without turning a third into 0.3333.
from decimal import Decimal, ROUND_HALF_UP
from fractions import Fraction
prices = [Decimal("1.10"), Decimal("2.20")]
subtotal = sum(prices)
tax = (subtotal * Decimal("0.05")).quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)
print("Subtotal:", subtotal, "Tax:", tax, "Total:", subtotal + tax)
print("Float sum:", 1.10 + 2.20)
flour = Fraction(2, 3)
print("Triple recipe needs", flour * 3, "cups, half recipe needs", flour / 2, "cups")Expected outputSubtotal: 3.30 Tax: 0.17 Total: 3.47
Float sum: 3.3000000000000003
Triple recipe needs 2 cups, half recipe needs 1/3 cups
Practise next
Python math and statistics exercises → Back to the lesson
Python Operators examplesPython Modules and Imports examplesPython random Module examplesNumPy Basics examples