- Core Definitions
- The
randomModule - The
mathModule - The
datetimeandtimeModules - Ways to Import
- Quick Reference
- Common Mistakes to Avoid
- Module: A file containing Python code (functions, variables, classes) that can be imported and used in other Python files. It's like a toolbox for a specific job.
import: The keyword used to bring a module's code into your current program so you can use it.- Library: A collection of related modules. The "Python Standard Library" is the collection of modules that comes included with Python.
You must import random before using these functions.
Returns a random integer N such that a <= N <= b.
import random
roll = random.randint(1, 6)Returns a single, random element from a sequence (like a list or tuple).
import random
players = ["Alice", "Bob", "Charlie"]
winner = random.choice(players)You must import math before using these.
Returns the square root of a number.
import math
side_length = math.sqrt(144) # 12.0A constant that holds the value of Pi (approx. 3.14159...).
import math
circumference = 2 * math.pi * 5Gets the current local date and time.
import datetime
now = datetime.datetime.now()
print(now)Formats a datetime object into a readable string.
# (continuing from above)
# %Y=Year, %m=month, %d=day, %H=Hour, %M=Minute, %S=Second
formatted = now.strftime("%Y-%m-%d %H:%M:%S")
print(formatted)Pauses the execution of your program for a given number of seconds.
import time
print("Waiting...")
time.sleep(3) # Pauses for 3 seconds
print("Done waiting!")Imports the entire module. You must use the module name as a prefix.
import random
roll = random.randint(1, 6)Imports a specific function directly. No prefix is needed.
from random import choice
winner = choice(["Alice", "Bob"])Imports a module and gives it a shorter nickname (alias).
import math as m
circumference = 2 * m.pi * 5| Function/Constant | Module | Description |
|---|---|---|
randint(a, b) |
random |
Random integer between a and b. |
choice(seq) |
random |
Random item from a sequence. |
sqrt(x) |
math |
Square root of x. |
pi |
math |
The constant Pi. |
datetime.now() |
datetime |
The current date and time. |
sleep(sec) |
time |
Pause the program for sec seconds. |
❌ Forgetting to import the module.
# Wrong: This will cause a NameError because Python doesn't know 'random'.
roll = random.randint(1, 6)✅ Always import first.
# Correct
import random
roll = random.randint(1, 6)❌ Using the wrong prefix after from...import.
# Wrong: 'choice' was imported directly, so it has no prefix.
from random import choice
winner = random.choice(["Alice", "Bob"]) # NameError: name 'random' is not defined✅ Call the function directly.
# Correct
from random import choice
winner = choice(["Alice", "Bob"])Happy coding! 🐍✨