📚 Using Built-in Modules
Using built-in modules in Python is like having access to a massive, well-organized library. Python comes with tons of pre-written, tested tools that solve common programming problems. Instead of writing everything from scratch, you can use these powerful modules to save time and effort.
Think of built-in modules as professional-grade tools that are already tested and ready to use - like having a toolbox full of the best tools for every job.
# 🎯 Built-in Modules Demo
# Import some popular built-in modules
import datetime
import random
import math
import os
print("🛠️ Built-in Modules Showcase:")
# DateTime - Working with dates and times
now = datetime.datetime.now()
print(f"📅 Current time: {now.strftime('%Y-%m-%d %H:%M:%S')}")
tomorrow = now + datetime.timedelta(days=1)
print(f"📅 Tomorrow: {tomorrow.strftime('%A, %B %d')}")
# Random - Generate random values
random_number = random.randint(1, 100)
colors = ['red', 'blue', 'green', 'yellow', 'purple']
random_color = random.choice(colors)
print(f"🎲 Random number: {random_number}")
print(f"🎨 Random color: {random_color}")
# Math - Mathematical operations
angle = 45
radians = math.radians(angle)
sine_value = math.sin(radians)
print(f"📐 Sin({angle}°) = {sine_value:.3f}")
print(f"🔢 Square root of 16: {math.sqrt(16)}")
# OS - System operations
current_directory = os.getcwd()
print(f"📁 Current directory: {os.path.basename(current_directory)}")
🎯 Understanding Built-in Modules
Python's standard library includes modules for almost every common programming task, from basic math to advanced networking.
📅 Working with Dates and Times
The datetime module helps you work with dates, times, and time calculations - essential for many applications.
# 📅 DateTime Module Deep Dive
import datetime
from datetime import date, time, timedelta
print("📅 DateTime Module Examples:")
# Current date and time
now = datetime.datetime.now()
today = date.today()
print(f"Right now: {now}")
print(f"Today's date: {today}")
# Creating specific dates
my_birthday = date(1990, 5, 15)
meeting_time = datetime.datetime(2024, 3, 20, 14, 30) # March 20, 2:30 PM
print(f"Birthday: {my_birthday}")
print(f"Meeting: {meeting_time}")
# Date arithmetic
one_week_later = today + timedelta(weeks=1)
thirty_days_ago = today - timedelta(days=30)
print(f"One week from today: {one_week_later}")
print(f"30 days ago: {thirty_days_ago}")
# Formatting dates
print(f"\nDate Formatting Examples:")
formats = [
("%Y-%m-%d", "Standard format"),
("%B %d, %Y", "Long format"),
("%m/%d/%Y", "US format"),
("%A", "Day of week"),
("%I:%M %p", "12-hour time")
]
for fmt, description in formats:
formatted = now.strftime(fmt)
print(f" {description}: {formatted}")
# Time calculations
age_days = (today - my_birthday).days
age_years = age_days // 365
print(f"\nAge calculation:")
print(f"Days since birthday: {age_days}")
print(f"Approximate age: {age_years} years")
🎲 Random Numbers and Choices
The random module helps you generate random numbers, make random selections, and add unpredictability to your programs.
# 🎲 Random Module Examples
import random
print("🎲 Random Module Showcase:")
# Random numbers
print("Random numbers:")
print(f" Random float (0-1): {random.random():.3f}")
print(f" Random integer (1-10): {random.randint(1, 10)}")
print(f" Random float (10-20): {random.uniform(10, 20):.2f}")
# Random choices
fruits = ['apple', 'banana', 'orange', 'grape', 'kiwi']
colors = ['red', 'blue', 'green', 'yellow', 'purple']
print(f"\nRandom selections:")
print(f" Random fruit: {random.choice(fruits)}")
print(f" Random color: {random.choice(colors)}")
# Multiple random items
random_fruits = random.sample(fruits, 3) # 3 unique items
print(f" 3 random fruits: {random_fruits}")
# Shuffling lists
deck = ['A', 'K', 'Q', 'J', '10', '9', '8', '7']
print(f" Original deck: {deck}")
random.shuffle(deck)
print(f" Shuffled deck: {deck}")
# Random with weights (some items more likely)
weighted_choices = random.choices(
population=['common', 'rare', 'legendary'],
weights=[70, 25, 5], # 70% common, 25% rare, 5% legendary
k=10 # Generate 10 items
)
print(f"\nWeighted random (10 items): {weighted_choices}")
# Simple password generator
letters = 'abcdefghijklmnopqrstuvwxyz'
digits = '0123456789'
all_chars = letters + letters.upper() + digits
password = ''.join(random.choice(all_chars) for _ in range(8))
print(f"Random password: {password}")
🔢 Mathematical Operations
The math module provides mathematical functions for calculations beyond basic arithmetic.
# 🔢 Math Module Examples
import math
print("🔢 Math Module Showcase:")
# Basic mathematical constants
print("Mathematical constants:")
print(f" Pi (π): {math.pi}")
print(f" Euler's number (e): {math.e}")
print(f" Infinity: {math.inf}")
# Rounding and absolute values
numbers = [3.14159, -2.7, 4.9, -1.1]
print(f"\nNumber operations:")
for num in numbers:
print(f" {num}: ceil={math.ceil(num)}, floor={math.floor(num)}, abs={abs(num)}")
# Powers and roots
print(f"\nPowers and roots:")
print(f" 2^8 = {math.pow(2, 8)}")
print(f" √64 = {math.sqrt(64)}")
print(f" ∛27 = {math.pow(27, 1/3):.2f}")
# Trigonometry (angles in radians)
angles_degrees = [0, 30, 45, 60, 90]
print(f"\nTrigonometry:")
for angle in angles_degrees:
radians = math.radians(angle)
sin_val = math.sin(radians)
cos_val = math.cos(radians)
print(f" {angle}°: sin={sin_val:.3f}, cos={cos_val:.3f}")
# Logarithms
print(f"\nLogarithms:")
print(f" log₁₀(100) = {math.log10(100)}")
print(f" ln(e) = {math.log(math.e):.3f}")
print(f" log₂(8) = {math.log2(8)}")
# Distance between two points
x1, y1 = 0, 0
x2, y2 = 3, 4
distance = math.sqrt((x2-x1)**2 + (y2-y1)**2)
print(f"\nDistance from ({x1},{y1}) to ({x2},{y2}): {distance}")
💻 System and File Operations
The os module provides tools for working with your computer's operating system and file system.
# 💻 OS Module Examples
import os
import sys
print("💻 OS Module Showcase:")
# System information
print("System information:")
print(f" Operating system: {os.name}")
print(f" Platform: {sys.platform}")
print(f" Python version: {sys.version.split()[0]}")
# Directory operations
current_dir = os.getcwd()
home_dir = os.path.expanduser("~")
print(f"\nDirectory information:")
print(f" Current directory: {os.path.basename(current_dir)}")
print(f" Home directory: {os.path.basename(home_dir)}")
# List files in current directory
print(f"\nFiles in current directory:")
try:
items = os.listdir(".")
files = [item for item in items if os.path.isfile(item)]
dirs = [item for item in items if os.path.isdir(item)]
print(f" 📁 Directories ({len(dirs)}): {dirs[:3]}...") # Show first 3
print(f" 📄 Files ({len(files)}): {files[:3]}...") # Show first 3
except PermissionError:
print(" Cannot list directory contents")
# Path operations
sample_path = "/home/user/documents/file.txt"
print(f"\nPath operations on: {sample_path}")
print(f" Directory: {os.path.dirname(sample_path)}")
print(f" Filename: {os.path.basename(sample_path)}")
print(f" Extension: {os.path.splitext(sample_path)[1]}")
# Join paths properly (cross-platform)
new_path = os.path.join("documents", "projects", "python", "script.py")
print(f" Joined path: {new_path}")
# Environment variables
print(f"\nEnvironment variables:")
user = os.environ.get("USER") or os.environ.get("USERNAME", "Unknown")
path_var = os.environ.get("PATH", "Not found")
print(f" Current user: {user}")
print(f" PATH variable: {len(path_var.split(os.pathsep))} directories")
🚀 Common Module Patterns
Understanding how to effectively use multiple modules together makes your programs more powerful and efficient.
Essential Built-in Modules Reference
Understanding core built-in modules enables effective use of Python's standard library for common programming tasks.
Module | Purpose | Key Functions | Common Use Cases |
---|---|---|---|
datetime | Date and time operations | now() , strftime() , timedelta() | Timestamps, scheduling, date arithmetic |
random | Random number generation | randint() , choice() , shuffle() | Games, sampling, simulations |
math | Mathematical functions | sqrt() , sin() , log() , pi | Calculations, geometry, statistics |
os | Operating system interface | getcwd() , listdir() , path.join() | File paths, directory operations |
sys | Python runtime environment | argv , path , version | Command line args, system info |
json | JSON data processing | loads() , dumps() , load() , dump() | API responses, configuration files |
re | Regular expressions | search() , match() , sub() | Text pattern matching, validation |
urllib | URL and web operations | urlopen() , urlparse() | Web requests, URL manipulation |
Using built-in modules effectively is a key skill for Python developers. The standard library provides tested, reliable solutions for most common programming tasks.
Test Your Knowledge
Test your understanding of Python's built-in modules:
What's Next?
Now that you understand how to use Python's built-in modules, you're ready to learn about module paths. Discover how Python finds modules and how to organize larger projects effectively.
Ready to continue? Check out our lesson on Module Paths.
Was this helpful?
Track Your Learning Progress
Sign in to bookmark tutorials and keep track of your learning journey.
Your progress is saved automatically as you read.