Welcome to Day 40 of your Python journey!
Today, we’ll explore three powerful standard library modules for mathematics, randomness, and data analysis:
-
math
– advanced mathematical operations -
random
– generating random numbers and selections -
statistics
– quick stats for numerical data
These are essential for everything from games and simulations to analytics and scientific computing.
🧮 1. The math
Module
Import it first:
import math
✅ Common Functions:
print(math.sqrt(16)) # 4.0
print(math.factorial(5)) # 120
print(math.pow(2, 3)) # 8.0
print(math.ceil(4.3)) # 5
print(math.floor(4.7)) # 4
✅ Constants:
print(math.pi) # 3.141592653589793
print(math.e) # 2.718281828459045
✅ Trigonometry:
print(math.sin(math.radians(30))) # 0.5
print(math.cos(math.radians(60))) # 0.5
print(math.tan(math.radians(45))) # 1.0
🎲 2. The random
Module
For generating random numbers and making selections:
import random
✅ Basic Random Numbers:
print(random.randint(1, 10)) # Random int between 1 and 10
print(random.uniform(1.5, 5.5)) # Random float between 1.5 and 5.5
✅ Random Choice:
colors = ['red', 'blue', 'green']
print(random.choice(colors)) # Randomly picks one color
✅ Shuffle a List:
cards = [1, 2, 3, 4, 5]
random.shuffle(cards)
print(cards)
✅ Sampling Multiple Items:
print(random.sample(colors, 2)) # Picks 2 unique colors
📊 3. The statistics
Module
Great for quick descriptive stats on numerical data:
import statistics
✅ Common Functions:
data = [2, 4, 4, 4, 5, 5, 7, 9]
print(statistics.mean(data)) # 5.0
print(statistics.median(data)) # 4.5
print(statistics.mode(data)) # 4
print(statistics.stdev(data)) # Standard deviation
print(statistics.variance(data)) # Variance
🛠️ Real-World Examples
🎮 Random Dice Roll:
dice_roll = random.randint(1, 6)
print("You rolled:", dice_roll)
📈 Data Analysis Summary:
sales = [120, 130, 115, 140, 150]
print("Average Sales:", statistics.mean(sales))
🎲 Simulation of 5 Random Points in a Unit Circle:
points = [(random.uniform(-1,1), random.uniform(-1,1)) for _ in range(5)]
print(points)
📌 Summary
-
math
= mathematical constants and advanced functions -
random
= randomness for games, simulations, and tests -
statistics
= quick stats for numerical data
🧪 Practice Challenge
- Generate 10 random integers between 1 and 100 and compute:
- Mean
- Median
- Standard deviation
- Create a function that simulates rolling two dice and summing the results.
- Use
math
to calculate the area of a circle with random radius between 1 and 10.