Module 10: Quick Reference
Modules & Imports Cheat Sheet
Import Styles
import math # Full module: math.sqrt(16) from math import sqrt, pi # Specific items: sqrt(16) import math as m # Alias: m.sqrt(16) from math import sqrt as sr # Function alias: sr(16)
math Module
| Function/Constant | Description | Example |
|---|---|---|
math.sqrt(x) | Square root | math.sqrt(25) → 5.0 |
math.ceil(x) | Round up | math.ceil(3.2) → 4 |
math.floor(x) | Round down | math.floor(3.9) → 3 |
math.pi | Pi constant | 3.141592653589793 |
math.pow(x, y) | x raised to y | math.pow(2, 3) → 8.0 |
math.fabs(x) | Absolute value (float) | math.fabs(-5) → 5.0 |
random Module
| Function | Description | Example |
|---|---|---|
random.randint(a, b) | Random int from a to b (inclusive) | randint(1, 6) → 4 |
random.choice(seq) | Random item from sequence | choice(["a","b"]) → "b" |
random.shuffle(list) | Shuffle list in place | Returns None, modifies list |
random.sample(seq, k) | k unique random items | sample([1,2,3], 2) → [3,1] |
random.random() | Random float 0.0 to 1.0 | 0.7234... |
datetime Module
from datetime import datetime now = datetime.now() now.year, now.month, now.day, now.hour, now.minute
| Format Code | Meaning | Example |
|---|---|---|
%Y | 4-digit year | 2025 |
%m | Month (01-12) | 06 |
%d | Day (01-31) | 15 |
%B | Full month name | June |
%A | Full weekday | Sunday |
%I | 12-hour clock | 02 |
%H | 24-hour clock | 14 |
%M | Minute | 30 |
%p | AM/PM | PM |
pip Commands (Terminal)
pip install package_name # Install a package pip install package==1.0.0 # Install specific version pip install --upgrade package # Upgrade a package pip uninstall package # Remove a package pip list # List installed packages pip freeze > requirements.txt # Save package list pip install -r requirements.txt # Install from file
Module Best Practices
# Use __name__ guard for test code if __name__ == "__main__": # This only runs when file is executed directly print("Testing...") # Import order: stdlib → third-party → your modules # Place all imports at the top of the file # Avoid: from module import *