Lesson 15 - Python Standard Libraries
Learning Objective
- Import and use two of Python’s standard library modules —
randomfor unpredictability anddatetimefor working with dates and times — without installing anything extra.
Introduction
Python ships with a huge standard library — modules you can import immediately, with no pip install needed.
This lesson covers two you’ll reach for constantly:
random, for anything involving chance or unpredictability.datetime, for reading and formatting the current date and time.
Code
import random
from datetime import datetime
# random
dice_roll = random.randint(1, 6)
print(f"Dice roll: {dice_roll}")
colors = ["red", "green", "blue", "yellow"]
chosen_color = random.choice(colors)
print(f"Chosen color: {chosen_color}")
shuffled = colors.copy()
random.shuffle(shuffled)
print(f"Shuffled: {shuffled}")
# datetime
now = datetime.now()
print(f"Current time: {now}")
print(f"Formatted: {now.strftime('%Y-%m-%d %H:%M:%S')}")
print(f"Day of week: {now.strftime('%A')}")Expected Output
Click to see expected output
Dice roll: 4
Chosen color: blue
Shuffled: ['yellow', 'red', 'blue', 'green']
Current time: 2026-07-22 14:03:11.842013
Formatted: 2026-07-22 14:03:11
Day of week: WednesdayYour exact dice roll, chosen color, shuffle order, and timestamp will differ every time you run this — that’s the whole point of random, and datetime.now() always reflects the real current time.
🔧 Under the Hood
Is random.randint() actually random?
random.randint() actually random?Not truly — it’s pseudo-random, generated by an algorithm seeded from something like the system clock, which is unpredictable enough for games, simulations, and shuffling, but not secure enough for things like passwords or encryption keys (Python has a separate secrets module for that).
You can force reproducible “randomness” with:
random.seed(42)Call it once at the top of a script, and every random call afterward will produce the same sequence every run, which is useful for testing.
strftime() (“string format time”) uses format codes like:
| Code | Meaning |
|---|---|
%Y | 4-digit year |
%A | Full weekday name |
%H | Hour (24-hour clock) |
%M | Minute |
%S | Second |
to turn a datetime object into exactly the text layout you want.
Student Challenge
Challenge 1 — Python only
Simulate rolling two dice 10,000 times and count how often each total comes up.
- Roll two 6-sided dice (
random.randint(1, 6)) 10,000 times. - Sum their values and store the count of each total in a dictionary.
- Print the totals sorted from 2 to 12 along with their frequencies.
Hint
sorted(roll_counts) sorts the dictionary’s keys, so results print from 2 to 12 in order instead of whatever order they happened to first appear.
Click to see solution
import random
roll_counts = {}
for _ in range(10000):
total = random.randint(1, 6) + random.randint(1, 6)
roll_counts[total] = roll_counts.get(total, 0) + 1
for total in sorted(roll_counts):
print(f"{total}: {roll_counts[total]} times")Challenge 2 — Robot
Have your BonicBot perform a randomized sequence of moves, with each one timestamped.
- Create a list of moves
MOVES = ["forward", "turn_left", "turn_right", "backward"]. - Loop 4 times, pick a random move using
random.choice(MOVES), print the current timestamp formatted as%H:%M:%S, and execute the corresponding movement. - Make sure the
if/elifchain covers every move inMOVES, including"backward".
Full movement methods are in the Python SDK reference.
Hint
Forgetting to add the matching elif branch means random.choice() could pick "backward" and nothing would happen — the if/elif chain has to cover every value in MOVES.
Click to see solution
import random
from datetime import datetime
from bonicbot_bridge import BonicBot
MOVES = ["forward", "turn_left", "turn_right", "backward"]
with BonicBot(host='192.168.0.188') as bot:
for step in range(4):
move = random.choice(MOVES)
timestamp = datetime.now().strftime('%H:%M:%S')
print(f"[{timestamp}] Step {step}: {move}")
if move == "forward":
bot.move_forward(speed=0.2, duration=1.0)
elif move == "turn_left":
bot.turn_left(speed=0.5, duration=1.0)
elif move == "turn_right":
bot.turn_right(speed=0.5, duration=1.0)
elif move == "backward":
bot.move_backward(speed=0.2, duration=1.0)
bot.stop()Library Quick Reference
Reflection Question
random.choice() picks unpredictably every time you run this patrol. For a robot moving in a physical space, name one situation where that unpredictability is genuinely useful, and one where you’d specifically want random.seed() instead so the behavior is repeatable.