Modules & Libraries
Import standard libraries (random, math, datetime, statistics, json) to execute rounding, generate random numbers, evaluate mean values, and parse JSON.
1. Importing Standard Modules
Modules are files containing pre-written Python code (functions and classes) that you can import using the import keyword. E.g., import math.
2. Selected Standard Libraries
- random: Provides utilities for random numbers:
random.randint(a, b)returns a random integer between a and b (inclusive);random.choice(list)picks a random item. - math: Holds advanced math operations:
math.ceil(x)rounds up,math.floor(x)rounds down, andmath.sqrt(x)computes square roots. - datetime: Manipulates dates and times. Format current dates to string variables using
now.strftime("%A"). - statistics: Computes central tendency values, including mean (average) and median (middle number):
statistics.mean(list). - json: Parses JSON string text to Python dictionaries (
json.loads()) and formats dictionaries back into JSON strings (json.dumps()).
💻 Python Code Examples
Example 1: Random Integers and Choice Selection
import random
num = random.randint(1, 10)
fruit = random.choice(["apple", "banana", "cherry"])
print(num)
print(fruit)
Description: Generates a random integer and picks a random string from a list.
Example 2: Math Rounding & Square Roots
import math
print(math.ceil(4.2)) # Rounds up
print(math.floor(4.8)) # Rounds down
print(math.sqrt(25)) # Square root
Description: Applies built-in math module operations to analyze values.
Example 3: Datetime & strftime Format Strings
import datetime
current = datetime.datetime.now()
print(current.strftime("%A")) # Weekday
print(current.strftime("%Y-%m-%d")) # YYYY-MM-DD
Description: Inspects dates and formats time data into human-readable strings.
Example 4: Calculating Mean and Median
import statistics
scores = [80, 90, 70, 100]
print(statistics.mean(scores)) # Average
print(statistics.median(scores)) # Mid-value
Description: Uses the statistics module to evaluate data attributes.
Example 5: Formatting Python Dictionaries to JSON
import json
info = {"name": "Ann", "age": 12}
json_str = json.dumps(info)
print(json_str)
print(type(json_str))
Description: Converts a Python dictionary object into a formatted JSON string (str).
Example 6: Parsing JSON Text Strings
import json
raw_json = '{"name": "Ann", "age": 12}'
data = json.loads(raw_json)
print(data["name"])
print(type(data))
Description: Parses a standard JSON string into a Python dictionary object.
🧠 Active Retrieval Quizzes
Answer the following 10 multiple-choice questions to test your storage strength.
Question 1: Which keyword is used to load an external or standard library module?
Question 2: Which random module function returns a random element from a list?
Question 3: What is the result of math.ceil(5.1)?
Question 4: What does current_time.strftime('%A') return?
Question 5: Which statistics module function computes the average of a list of numbers?
Question 6: Which statistics module function computes the middle value of a sorted list?
Question 7: Which function converts a Python dictionary to a JSON string?
Question 8: Which function parses a JSON string into a Python dictionary?
Question 9: What does math.floor(3.9) evaluate to?
Question 10: What is the return type of json.dumps()?
🖥️ Output Prediction Challenges
Read each code snippet carefully, analyze its execution flow, and predict the exact string result written to the console.
Predict the output of the code snippet below. Type the exact output in the console.
import math
print(math.floor(3.9))
Predict the output of the code snippet below. Type the exact output in the console.
import math
print(math.ceil(3.1))
Predict the output of the code snippet below. Type the exact output in the console.
import statistics
print(statistics.mean([10, 20, 30]))
Predict the output of the code snippet below. Type the exact output in the console.
import json
d = json.loads('{"x": 10}')
print(d["x"])
Predict the output of the code snippet below. Type the exact output in the console.
import math
print(type(math.sqrt(9)))
🎮 Interactive Code Playground
Type your own Python code below and click "Run Code" to execute it instantly in your browser!
Console ready.
Stuck on any concept, or want to explore an edge case? Don't hesitate to ask follow-up questions to your instructor! Active questioning helps build storage strength.
📋 Progress Status
📌 Check the box above to mark this weekend's lesson complete. Your dashboard status ring will update automatically.