← Back to Hub
Module 5 Week 14 • Standard libraries math, random, datetime, statistics, and json parser

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, and math.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?

Explanation: The import keyword loads modules in Python.

Question 2: Which random module function returns a random element from a list?

Explanation: random.choice() picks a random element from a list.

Question 3: What is the result of math.ceil(5.1)?

Explanation: math.ceil() rounds a float up to the next nearest whole integer (6).

Question 4: What does current_time.strftime('%A') return?

Explanation: %A format placeholder returns the full weekday name (e.g., 'Monday').

Question 5: Which statistics module function computes the average of a list of numbers?

Explanation: statistics.mean() calculates the arithmetic average of a list of values.

Question 6: Which statistics module function computes the middle value of a sorted list?

Explanation: statistics.median() calculates the middle value of a sorted collection.

Question 7: Which function converts a Python dictionary to a JSON string?

Explanation: json.dumps() serializes a Python object to a JSON formatted string.

Question 8: Which function parses a JSON string into a Python dictionary?

Explanation: json.loads() deserializes a JSON string into a Python dictionary object.

Question 9: What does math.floor(3.9) evaluate to?

Explanation: math.floor() rounds decimals down to the nearest integer, returning 3.

Question 10: What is the return type of json.dumps()?

Explanation: json.dumps() converts a python object into a raw text string.

🖥️ Output Prediction Challenges

Read each code snippet carefully, analyze its execution flow, and predict the exact string result written to the console.

Challenge 1 of 5

Predict the output of the code snippet below. Type the exact output in the console.

import math
print(math.floor(3.9))
Console ready. Type your prediction below...
Challenge 2 of 5

Predict the output of the code snippet below. Type the exact output in the console.

import math
print(math.ceil(3.1))
Console ready. Type your prediction below...
Challenge 3 of 5

Predict the output of the code snippet below. Type the exact output in the console.

import statistics
print(statistics.mean([10, 20, 30]))
Console ready. Type your prediction below...
Challenge 4 of 5

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"])
Console ready. Type your prediction below...
Challenge 5 of 5

Predict the output of the code snippet below. Type the exact output in the console.

import math
print(type(math.sqrt(9)))
Console ready. Type your prediction below...

🎮 Interactive Code Playground

Type your own Python code below and click "Run Code" to execute it instantly in your browser!

📝 Python Code Editor
Python WebAssembly runtime is unloaded. Click 'Run Code' to load.
🖥️ Output Console
Console ready.
💬 Teacher Consultation

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

Lesson Complete?

📌 Check the box above to mark this weekend's lesson complete. Your dashboard status ring will update automatically.