Lab: Build a Hypotenuse Calculator
Scenario: You need to calculate the longest side of a triangle (hypotenuse) given two sides. This is used in game development (distance between players) and GPS calculations.
import math
def calculate_hypotenuse():
print("--- Hypotenuse Calculator ---")
# Get user input
try:
side_a = float(input("Enter length of side A: "))
side_b = float(input("Enter length of side B: "))
# Calculation using Pythagorean theorem: c = sqrt(a^2 + b^2)
hypotenuse = math.sqrt(math.pow(side_a, 2) + math.pow(side_b, 2))
# Or use the built-in shortcut!
hypotenuse_fast = math.hypot(side_a, side_b)
print(f"The Hypotenuse is: {hypotenuse:.2f}")
print(f"Verified with math.hypot: {hypotenuse_fast:.2f}")
except ValueError:
print("Error: Please enter valid numbers only.")
# Run the lab
calculate_hypotenuse()
Lab 1: The “Smart Painter” (Beginner)
Scenario: You are building an app for a painting company. A user enters the size of a wall, and your program must calculate exactly how many cans of paint they need to buy. You cannot buy “half a can,” so you must always round up.
Concepts Used: math.ceil() (Ceiling function), Basic Arithmetic.
The Logic:
- Calculate Area = Height × Width.
- Divide Area by the coverage of one paint can.
- Round the result UP to the nearest integer.
import math
def paint_calculator():
print("--- 🏠 Smart Painter Tool ---")
# Constants
COVERAGE_PER_CAN = 50 # One can covers 50 square feet
try:
height = float(input("Enter wall height (ft): "))
width = float(input("Enter wall width (ft): "))
area = height * width
cans_needed = area / COVERAGE_PER_CAN
# Crucial Step: We use ceil because 2.1 cans means we need to buy 3 cans
total_cans = math.ceil(cans_needed)
print(f"Total Area: {area} sq. ft")
print(f"Exact Calculation: {cans_needed:.2f} cans")
print(f"👉 You need to buy: {total_cans} cans")
except ValueError:
print("Please enter valid numbers!")
paint_calculator()Why math.ceil? If the result is 2.1, standard rounding would give you 2. But in real life, you need that extra bit of paint, so you must buy the 3rd can. math.ceil handles this logic perfectly.
Lab 2: The “Server Batch Processor” (Intermediate)
Scenario: You are a DevOps Engineer. You have a massive list of 10,000 database records to process. Your server can only handle 12 records per batch. You need to know:
- How many full batches will run?
- How many records are left over for the final small batch?
Concepts Used: math.floor(), math.fmod() (Floating Point Modulo).
import math
def batch_scheduler():
print("--- 🖥️ Server Batch Processor ---")
total_records = 10000
batch_size = 12
# 1. Calculate full batches (Round DOWN)
# simple division gives float, floor gives integer part
full_batches = math.floor(total_records / batch_size)
# 2. Calculate remaining records
# fmod is more precise for floats, but works great here too
leftover = math.fmod(total_records, batch_size)
print(f"Total Records: {total_records}")
print(f"Batch Size: {batch_size}")
print(f"---------------------------")
print(f"✅ Full Batches to Run: {full_batches}")
print(f"⚠️ Records in Final Batch: {int(leftover)}")
batch_scheduler()Lab 3: The “Log Anomaly Detector” (Advanced)
Scenario: You are analyzing server response times. You want to detect “outliers”—requests that took way too long. A common statistical method is to find values that are far from the average (Standard Deviation).
Concepts Used: math.sqrt(), math.pow(), Mean (Average).
import math
def analyze_latency():
print("--- 📊 Log Anomaly Detector ---")
# Response times in milliseconds (ms)
# Notice 500 is very high compared to others
latencies = [12, 15, 14, 13, 16, 12, 500, 14, 15]
n = len(latencies)
# Step 1: Calculate Mean (Average)
mean = sum(latencies) / n
# Step 2: Calculate Variance
# Variance = Average of squared differences from the Mean
variance_sum = 0
for x in latencies:
variance_sum += math.pow(x - mean, 2)
variance = variance_sum / n
# Step 3: Standard Deviation is sqrt of Variance
std_dev = math.sqrt(variance)
print(f"Average Latency: {mean:.2f} ms")
print(f"Standard Deviation: {std_dev:.2f}")
# Step 4: Detect Anomalies (Simple Logic: > Mean + 2 * StdDev)
threshold = mean + (2 * std_dev)
print(f"Alert Threshold: {threshold:.2f} ms")
print("\n--- Scanning Logs ---")
for lat in latencies:
if lat > threshold:
print(f"🚨 ANOMALY DETECTED: {lat} ms is too slow!")
analyze_latency()Note: Python 3.4+ has a statistics module that does this automatically, but manually writing the math logic is excellent practice to understand the algorithm behind the tool.
Lab 4: The “Password Entropy Checker” (Architect Level)
Scenario: As a DevSecOps Architect, you don’t just check if a password has 8 characters. You check its Entropy (mathematical randomness). Higher entropy means it is harder for hackers to crack.
Formula: Entropy=Length×log2(PoolSize)
Pool Sizes:
- Only Numbers = 10
- Lower Case = 26
- Lower + Upper = 52
- Lower + Upper + Numbers = 62
- All (including symbols) ≈ 94
Concepts Used: math.log2() (Logarithm base 2).
import math
def check_entropy():
print("--- 🔐 Password Entropy Calculator ---")
password = input("Enter a test password: ")
length = len(password)
# Determine Pool Size (Simplified logic for demo)
pool_size = 0
if password.isdigit():
pool_size = 10
elif password.isalpha():
pool_size = 52 # Assuming mixed case
else:
pool_size = 94 # Assuming complex mix
# Calculate Entropy using math.log2
# Logic: How many 'bits' of information are in this password?
entropy = length * math.log2(pool_size)
print(f"\nPassword Length: {length}")
print(f"Character Pool Size: {pool_size}")
print(f"-------------------------------")
print(f"🧪 Entropy Score: {entropy:.2f} bits")
# Architect's Verdict
if entropy < 28:
print("Verdict: 🔴 Very Weak (Instant Crack)")
elif entropy < 60:
print("Verdict: 🟡 Moderate (OK for simple accounts)")
else:
print("Verdict: 🟢 Strong (DevSecOps Approved!)")
check_entropy()