python
examples
examples.py🐍python
"""
06 - Modules & Packages: Examples
Run this file to see module usage in action!
"""
print("=" * 60)
print("MODULES & PACKAGES - EXAMPLES")
print("=" * 60)
# =============================================================================
# 1. IMPORTING MODULES
# =============================================================================
print("\n--- 1. Importing Modules ---\n")
# Import entire module
import math
print(f"math.pi = {math.pi}")
print(f"math.sqrt(16) = {math.sqrt(16)}")
print(f"math.sin(math.pi/2) = {math.sin(math.pi/2)}")
# Import with alias
import math as m
print(f"\nWith alias: m.floor(3.7) = {m.floor(3.7)}")
# Import specific items
from math import ceil, factorial
print(f"\nSpecific imports:")
print(f"ceil(3.2) = {ceil(3.2)}")
print(f"factorial(5) = {factorial(5)}")
# Import with alias
from math import sqrt as square_root
print(f"square_root(25) = {square_root(25)}")
# =============================================================================
# 2. OS MODULE
# =============================================================================
print("\n--- 2. os Module ---\n")
import os
# Current working directory
print(f"Current directory: {os.getcwd()}")
# List directory contents (first 5 items)
items = os.listdir('.')
print(f"Directory contents: {items[:5]}...")
# Path operations
print(f"\nPath operations:")
print(f"os.path.exists('.'): {os.path.exists('.')}")
print(f"os.path.isdir('.'): {os.path.isdir('.')}")
print(f"os.path.join('folder', 'file.txt'): {os.path.join('folder', 'file.txt')}")
print(f"os.path.splitext('document.pdf'): {os.path.splitext('document.pdf')}")
print(f"os.path.basename('/path/to/file.txt'): {os.path.basename('/path/to/file.txt')}")
print(f"os.path.dirname('/path/to/file.txt'): {os.path.dirname('/path/to/file.txt')}")
# Environment variables
print(f"\nEnvironment variable HOME: {os.environ.get('HOME', 'Not set')}")
# =============================================================================
# 3. SYS MODULE
# =============================================================================
print("\n--- 3. sys Module ---\n")
import sys
print(f"Python version: {sys.version}")
print(f"Python version info: {sys.version_info.major}.{sys.version_info.minor}")
print(f"Platform: {sys.platform}")
print(f"Executable: {sys.executable}")
# Command line arguments (when running from terminal)
print(f"Command line args: {sys.argv}")
# Module search path (first 3)
print(f"\nModule search path (first 3):")
for path in sys.path[:3]:
print(f" {path}")
# =============================================================================
# 4. DATETIME MODULE
# =============================================================================
print("\n--- 4. datetime Module ---\n")
from datetime import datetime, date, time, timedelta
# Current date and time
now = datetime.now()
print(f"Now: {now}")
print(f"Today: {date.today()}")
# Formatting
print(f"\nFormatting:")
print(f" %Y-%m-%d: {now.strftime('%Y-%m-%d')}")
print(f" %B %d, %Y: {now.strftime('%B %d, %Y')}")
print(f" %I:%M %p: {now.strftime('%I:%M %p')}")
# Parsing
parsed = datetime.strptime("2024-06-15 14:30:00", "%Y-%m-%d %H:%M:%S")
print(f"\nParsed date: {parsed}")
# Date arithmetic
tomorrow = date.today() + timedelta(days=1)
next_week = date.today() + timedelta(weeks=1)
print(f"\nTomorrow: {tomorrow}")
print(f"Next week: {next_week}")
# Difference between dates
date1 = date(2024, 12, 31)
date2 = date.today()
difference = date1 - date2
print(f"Days until 2024-12-31: {difference.days}")
# =============================================================================
# 5. RANDOM MODULE
# =============================================================================
print("\n--- 5. random Module ---\n")
import random
# Random float [0.0, 1.0)
print(f"random.random(): {random.random():.4f}")
# Random integer
print(f"random.randint(1, 100): {random.randint(1, 100)}")
# Random choice
fruits = ['apple', 'banana', 'cherry', 'date']
print(f"random.choice({fruits}): {random.choice(fruits)}")
# Multiple choices
print(f"random.choices(fruits, k=3): {random.choices(fruits, k=3)}")
# Sample without replacement
print(f"random.sample(fruits, k=2): {random.sample(fruits, k=2)}")
# Shuffle
numbers = [1, 2, 3, 4, 5]
random.shuffle(numbers)
print(f"Shuffled [1,2,3,4,5]: {numbers}")
# Random with seed (reproducible)
random.seed(42)
print(f"Seeded random: {random.random():.4f}")
# =============================================================================
# 6. JSON MODULE
# =============================================================================
print("\n--- 6. json Module ---\n")
import json
# Python dict to JSON string
data = {
"name": "Alice",
"age": 25,
"hobbies": ["reading", "coding"],
"address": {
"city": "New York",
"zip": "10001"
}
}
json_str = json.dumps(data, indent=2)
print("JSON string:")
print(json_str)
# JSON string to Python dict
parsed = json.loads(json_str)
print(f"\nParsed back: {parsed['name']}, {parsed['age']}")
# Pretty print complex data
complex_data = {"users": [{"id": 1, "name": "Alice"}, {"id": 2, "name": "Bob"}]}
print(f"\nPretty JSON:")
print(json.dumps(complex_data, indent=2, sort_keys=True))
# =============================================================================
# 7. COLLECTIONS MODULE
# =============================================================================
print("\n--- 7. collections Module ---\n")
from collections import Counter, defaultdict, namedtuple, deque, OrderedDict
# Counter - count occurrences
text = "abracadabra"
counter = Counter(text)
print(f"Counter('{text}'): {counter}")
print(f"Most common 3: {counter.most_common(3)}")
# defaultdict - dict with default values
print("\ndefaultdict:")
dd = defaultdict(list)
dd['fruits'].append('apple')
dd['fruits'].append('banana')
dd['vegetables'].append('carrot')
print(f" {dict(dd)}")
# namedtuple - tuple with named fields
print("\nnamedtuple:")
Point = namedtuple('Point', ['x', 'y'])
p = Point(3, 4)
print(f" Point: {p}")
print(f" x={p.x}, y={p.y}")
# deque - double-ended queue
print("\ndeque:")
dq = deque([1, 2, 3])
dq.appendleft(0)
dq.append(4)
print(f" After appendleft(0) and append(4): {dq}")
print(f" popleft(): {dq.popleft()}")
print(f" After popleft: {dq}")
# =============================================================================
# 8. PATHLIB MODULE
# =============================================================================
print("\n--- 8. pathlib Module ---\n")
from pathlib import Path
# Create path object
p = Path('.')
print(f"Current path: {p.absolute()}")
# Path properties
print(f"\nPath properties:")
print(f" exists: {p.exists()}")
print(f" is_dir: {p.is_dir()}")
# Build paths
new_path = Path('folder') / 'subfolder' / 'file.txt'
print(f"\nBuilt path: {new_path}")
print(f" parent: {new_path.parent}")
print(f" name: {new_path.name}")
print(f" stem: {new_path.stem}")
print(f" suffix: {new_path.suffix}")
# List Python files in current directory
print("\nPython files in current directory:")
py_files = list(Path('.').glob('*.py'))[:5]
for f in py_files:
print(f" {f}")
# =============================================================================
# 9. RE MODULE (REGULAR EXPRESSIONS)
# =============================================================================
print("\n--- 9. re Module ---\n")
import re
text = "Contact us at support@email.com or sales@company.org"
# Find all emails
emails = re.findall(r'\S+@\S+', text)
print(f"Found emails: {emails}")
# Search for pattern
match = re.search(r'\d+', "Order #12345")
if match:
print(f"Found number: {match.group()}")
# Replace
new_text = re.sub(r'\d+', 'XXX', "Phone: 555-1234")
print(f"Replaced: {new_text}")
# Split
parts = re.split(r'[,\s]+', "apple, banana cherry,date")
print(f"Split result: {parts}")
# =============================================================================
# 10. ITERTOOLS MODULE
# =============================================================================
print("\n--- 10. itertools Module ---\n")
import itertools
# Count (infinite)
counter = itertools.count(10, 2)
print(f"count(10, 2): {[next(counter) for _ in range(5)]}")
# Cycle (infinite)
cycler = itertools.cycle(['A', 'B', 'C'])
print(f"cycle(['A','B','C']): {[next(cycler) for _ in range(7)]}")
# Chain
chained = list(itertools.chain([1, 2], [3, 4], [5, 6]))
print(f"chain([1,2], [3,4], [5,6]): {chained}")
# Combinations
combs = list(itertools.combinations('ABC', 2))
print(f"combinations('ABC', 2): {combs}")
# Permutations
perms = list(itertools.permutations('AB', 2))
print(f"permutations('AB', 2): {perms}")
# Product (cartesian product)
prod = list(itertools.product('AB', '12'))
print(f"product('AB', '12'): {prod}")
# =============================================================================
# 11. FUNCTOOLS MODULE
# =============================================================================
print("\n--- 11. functools Module ---\n")
from functools import reduce, lru_cache, partial
# reduce - accumulate values
numbers = [1, 2, 3, 4, 5]
product = reduce(lambda x, y: x * y, numbers)
print(f"reduce (product of {numbers}): {product}")
# lru_cache - memoization
@lru_cache(maxsize=100)
def fibonacci(n):
if n < 2:
return n
return fibonacci(n - 1) + fibonacci(n - 2)
print(f"\nFibonacci with cache:")
print(f"fibonacci(30) = {fibonacci(30)}")
print(f"Cache info: {fibonacci.cache_info()}")
# partial - partial function application
def power(base, exponent):
return base ** exponent
square = partial(power, exponent=2)
cube = partial(power, exponent=3)
print(f"\nPartial functions:")
print(f"square(5) = {square(5)}")
print(f"cube(5) = {cube(5)}")
# =============================================================================
# 12. IF __NAME__ == "__MAIN__"
# =============================================================================
print("\n--- 12. if __name__ == '__main__' ---\n")
print(f"Current module name: {__name__}")
print("This file is being run directly (not imported)")
print("If this were imported, __name__ would be the module name")
# =============================================================================
# 13. PRACTICAL EXAMPLE - CREATING A SIMPLE MODULE
# =============================================================================
print("\n--- 13. Module Example (inline demo) ---\n")
# In a real scenario, this would be in a separate file
class MyMathModule:
"""A simple math module example."""
PI = 3.14159
@staticmethod
def add(a, b):
return a + b
@staticmethod
def multiply(a, b):
return a * b
@staticmethod
def circle_area(radius):
return MyMathModule.PI * radius ** 2
# Using the module
mm = MyMathModule
print(f"PI: {mm.PI}")
print(f"add(3, 5): {mm.add(3, 5)}")
print(f"circle_area(5): {mm.circle_area(5):.2f}")
print("\n" + "=" * 60)
print("END OF EXAMPLES")
print("=" * 60)