Python from Zero to One – Part 7: Master math, random, and datetime in 5 Minutes
This tutorial reviews three import patterns, demonstrates essential functions of the math, random, and datetime built‑in modules with concrete code examples, combines them in a practical exercise, highlights four common beginner pitfalls with fixes, and provides short post‑lesson tasks.
Module import core templates
# Template 1: import the whole module (generic, less error‑prone)
import module_name
# Call: module_name.function_name()
# Template 2: import specific functions (concise, common)
from module_name import function1, function2
# Call: function_name()
# Template 3: import module with alias (simplify usage)
import module_name as alias
# Call: alias.function_name()High‑frequency built‑in modules (hands‑on)
math module (mathematical calculations)
# Example 1: import the whole math module (Template 1)
import math
print(math.sqrt(16)) # square root → 4.0
print(math.pi) # π → 3.141592653589793
print(math.ceil(3.2)) # round up → 4
print(math.floor(3.8)) # round down → 3
print(math.pow(2, 5)) # 2⁵ → 32.0
print(math.abs(-10)) # absolute value → 10
# Example 2: import specific functions (Template 2, more concise)
from math import sqrt, pi, ceil
print(sqrt(25)) # 5.0
print(pi) # 3.141592653589793
print(ceil(4.1)) # 5random module (random number generation)
# Example 1: import the whole module
import random
print(random.randint(1, 10)) # random integer 1‑10 inclusive
print(random.random()) # random float 0 ≤ x < 1
print(random.choice(["A", "B", "C"])) # pick one element
print(random.sample([1,2,3,4,5], 3)) # three distinct elements
# Example 2: import with alias (Template 3)
import random as r
print(r.randint(10, 20)) # random integer 10‑20datetime module (time handling)
# Example 1: import specific functions (most common, avoid redundancy)
from datetime import datetime, timedelta
# 1. Get current time
now = datetime.now()
print(now) # e.g., 2024-05-11 15:30:00.123456
# 2. Format time (year-month-day hour:minute:second)
print(now.strftime("%Y-%m-%d %H:%M:%S"))
# 3. Time arithmetic (add 1 day, subtract 2 hours)
print(now + timedelta(days=1)) # same time tomorrow
print(now - timedelta(hours=2)) # two hours ago
# Example 2: import the whole module (fallback)
import datetime
print(datetime.datetime.now()) # need full pathIntegrated practice (combine the three modules)
# Real‑world example: generate random scores, compute average, record time
from math import mean
import random
from datetime import datetime
# 1. Generate 10 random scores between 60 and 100
scores = [random.randint(60, 100) for _ in range(10)]
print("Random scores:", scores)
# 2. Compute average using math.mean
avg_score = mean(scores)
print("Average score:", round(avg_score, 1))
# 3. Record current time
now_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
print("Score generation time:", now_time)Four common beginner pitfalls (with solutions)
❌ Pitfall 1: Calling a non‑existent attribute of math, e.g., math.square.
Solution: Verify the exact function name (use pow for exponentiation, ceil for rounding up).
❌ Pitfall 2: Swapping arguments in random.randint(a, b) so that a > b.
Solution: Ensure the first argument is less than or equal to the second (e.g., randint(1, 10), not randint(10, 1)).
❌ Pitfall 3: ImportError when importing datetime due to wrong syntax.
Solution: Use either import datetime (module) or from datetime import datetime (class), but do not mix the two forms.
❌ Pitfall 4: Installing third‑party packages fails with mirror errors like “webpage parsing failed”.
Solution: Switch to a different mirror (e.g., from Tsinghua to USTC) or use the default source.
Post‑lesson mini‑tasks (copy‑paste code)
# 1. Using math: compute 5³, sqrt(100), and abs(-15)
import math
print(math.pow(5, 3))
print(math.sqrt(100))
print(math.abs(-15))
# 2. Using random: generate a number 1‑100, check if >50
import random
num = random.randint(1, 100)
print("Random number:", num)
print("Greater than 50:", num > 50)
# 3. Using datetime: get current date formatted as YYYY‑MM‑DD
from datetime import datetime
print(datetime.now().strftime("%Y-%m-%d"))Key takeaways
Built‑in modules require no installation; mastering math, random, and datetime covers most beginner scenarios.
After these examples, you should be comfortable with mathematical operations, random generation, and time handling using the import templates.
When errors occur, first check function name spelling, import style, and mirror selection for package installation.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
liandk
Seasoned Java and mobile developer with years of experience, specializing in mini‑programs, public accounts, and full‑stack front‑end development. In the AI era, I continuously learn to broaden my knowledge and evolve. I revived a public account I started a decade ago during a dessert‑startup venture, using code as a vessel and knowledge as a companion. I share personal projects, technical articles, programming tips, and growth insights—let’s improve together and set sail.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
