Python Libraries

"The most powerful line of code in Python is rarely a complex algorithm, but a simple import statement."- Gemini 2025

Learning Objectives
  • Understand what Python libraries are and why they're essential
  • Know how to find, install and import libraries
  • Have hands-on experience with 4 key libraries: datetime, requests, matplotlib, and pandas
  • Be able to evaluate and choose appropriate libraries for your projects

Finding and Using Python Libraries

What Are Python Libraries?

Think of Python libraries like a toolbox. Python gives you basic tools (hammers, screwdrivers), but libraries give you specialized power tools that make complex jobs simple.

Key Websites to Bookmark
Finding and Evaluating Libraries
Where to Look
  1. PyPI: Search by functionality (e.g., "web scraping", "data analysis")
  2. GitHub: Look for Python projects with high stars
  3. Documentation sites: Real Python, Python.org tutorials
  4. Community recommendations: Stack Overflow, Reddit r/Python
Evaluation Criteria
  • Activity: Recent commits and releases
  • Documentation: Clear, comprehensive docs
  • Community: GitHub stars, downloads, active issues
  • Codebase: Look for clean, organized code in open-source libraries
  • License: Compatible with your project
Installation and Import Basics
 # > shell commands

# Install a single library
pip install requests

# Install multiple libraries
pip install pandas matplotlib datetime

# Use virtual environments
python -m venv myproject
source myproject/bin/activate  # Linux/Mac
# Different ways to import
import requests
import pandas as pd
import matplotlib.pyplot as plt
from datetime import datetime

# Check what's available
import datetime
print(dir(datetime))  # See all available functions
Managing Dependencies with requirements.txt
Creating requirements.txt
 # > shell commands

# Generate from current environment
pip freeze > requirements.txt

# Or create manually
echo "requests==2.31.0" > requirements.txt
echo "pandas==2.0.3" >> requirements.txt
echo "matplotlib==3.7.2" >> requirements.txt
Using requirements.txt
 # > shell commands

# Install all dependencies
pip install -r requirements.txt

# Upgrade all packages
pip install -r requirements.txt --upgrade

# Install in new environment
python -m venv newproject
source newproject/bin/activate
pip install -r requirements.txt
Sample requirements.txt file
# requirements.txt

# Core data science libraries
pandas==2.0.3
numpy==1.25.2
matplotlib==3.7.2

# Web requests
requests==2.31.0

# Best Practice: specify minimum versions
# scipy>=1.10.0
# jupyter>=1.0.0

# Comments explain why you need each library
plotly==5.15.0  # Interactive visualizations
seaborn==0.12.2  # Statistical plotting

Datetime - Working with Dates and Times

Basic Examples
from datetime import datetime, date, timedelta

# Current date and time
now = datetime.now()
today = date.today()
print(f"Current time: {now}")
print(f"Today's date: {today}")

# Creating specific dates
birthday = date(1990, 5, 15)
meeting = datetime(2024, 12, 25, 14, 30)  # Dec 25, 2024 at 2:30 PM

# Date arithmetic
next_week = today + timedelta(days=7)
age_in_days = today - birthday
print(f"Next week: {next_week}")
print(f"Age in days: {age_in_days.days}")
Formatting and Parsing
# Formatting dates
formatted = now.strftime("%Y-%m-%d %H:%M:%S")
print(f"Formatted: {formatted}")

# Parsing strings to dates
date_string = "2024-03-15"
parsed_date = datetime.strptime(date_string, "%Y-%m-%d")
print(f"Parsed: {parsed_date}")
Real-World Example: Age Calculator
from datetime import date

def calculate_age(birth_date):
    today = date.today()
    age = today.year - birth_date.year

    # Adjust if birthday hasn't occurred this year
    if today.month < birth_date.month or \
        (today.month == birth_date.month and today.day < birth_date.day):
        age -= 1

    return age

# Usage
birthday = date(1995, 8, 20)
age = calculate_age(birthday)
print(f"Age: {age} years old")

Requests - HTTP Made Simple

Basic Examples
import requests

# Simple GET request
response = requests.get('https://api.github.com/users/octocat')
print(f"Status: {response.status_code}")
print(f"Data: {response.json()}")

# POST request with data
data = {'name': 'John', 'age': 30}
response = requests.post('https://httpbin.org/post', json=data)
print(response.json())

# Handling errors gracefully
try:
    response = requests.get('https://api.github.com/users/nonexistentuser')
    response.raise_for_status()  # Raises exception for bad status codes
    except requests.exceptions.RequestException as e:
    print(f"Error: {e}")
Real-World Example: Random Quote Fetcher
import requests

def get_random_quote():
    """Fetch a random inspirational quote"""
    url = "https://zenquotes.io/api/random"
    
    try:
        response = requests.get(url, timeout=5)
        response.raise_for_status()
        
        data = response.json()
        # ZenQuotes returns an array with one quote
        quote_data = data[0]
        return f'"{quote_data["q"]}" - {quote_data["a"]}'
    except requests.exceptions.RequestException as e:
        return f"Error fetching quote: {e}"

# Usage
quote = get_random_quote()
print(quote)

Matplotlib - Data Visualization

Basic Plotting
import matplotlib.pyplot as plt

# Simple line plot
months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun']
sales = [1200, 1500, 1100, 1800, 2000, 1700]

plt.figure(figsize=(10, 6))
plt.plot(months, sales, marker='o')
plt.title('Monthly Sales')
plt.xlabel('Month')
plt.ylabel('Sales ($)')
plt.grid(True)
plt.show()

# Bar chart
categories = ['Product A', 'Product B', 'Product C', 'Product D']
values = [23, 45, 56, 78]

plt.figure(figsize=(8, 6))
plt.bar(categories, values, color=['red', 'blue', 'green', 'orange'])
plt.title('Product Sales Comparison')
plt.ylabel('Units Sold')
plt.xticks(rotation=45)
plt.tight_layout()
plt.show()
Multiple Plots Example
import matplotlib.pyplot as plt

# Create subplots
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(12, 5))

# Left plot: Line chart
months = ['Q1', 'Q2', 'Q3', 'Q4']
revenue = [50000, 65000, 70000, 80000]
ax1.plot(months, revenue, marker='s', linewidth=2)
ax1.set_title('Quarterly Revenue')
ax1.set_ylabel('Revenue ($)')

# Right plot: Pie chart
expenses = [25000, 15000, 10000, 8000]
labels = ['Salaries', 'Rent', 'Marketing', 'Other']
ax2.pie(expenses, labels=labels, autopct='%1.1f%%')
ax2.set_title('Expense Breakdown')

plt.tight_layout()
plt.show()

Pandas - Data Analysis Made Easy

Basic DataFrame Operations & Simple Data Analysis
import pandas as pd

# Creating a DataFrame
data = {
'Name': ['Alice', 'Bob', 'Charlie', 'Diana'],
'Age': [25, 30, 35, 28],
'Department': ['Sales', 'IT', 'Marketing', 'Sales'],
'Salary': [60000, 80000, 70000, 65000]
}
df = pd.DataFrame(data)
print(df)

print("Dataset Info:")
print(f"Shape: {df.shape}")
print(f"Columns: {list(df.columns)}")
print("\nFirst few rows:")
print(df.head())

# Basic statistics
print(f"\nAverage salary: ${df['Salary'].mean():,.2f}")
print(f"Youngest employee: {df['Age'].min()} years old")
print(f"Oldest employee: {df['Age'].max()} years old")

# Filtering data
sales_team = df[df['Department'] == 'Sales']
print(f"\nSales team members: {len(sales_team)}")
print(sales_team[['Name', 'Salary']])

# Grouping
dept_stats = df.groupby('Department')['Salary'].agg(['mean', 'count'])
print(f"\nDepartment salary statistics:")
print(dept_stats)
Loading External Data
# Load from CSV (most common)
df = pd.read_csv('employees.csv')

# Load from Excel
df = pd.read_excel('data.xlsx') -->

print(df)

Example Project: Personal Finance Tracker

import requests
import pandas as pd
import matplotlib.pyplot as plt
from datetime import datetime, timedelta

class FinanceTracker:
    def __init__(self):
        self.transactions = []

    def add_transaction(self, amount, category, description, date=None):
        """Add a new transaction"""
        if date is None:
            date = datetime.now().date()
        
        transaction = {
            'date': date,
            'amount': amount,
            'category': category,
            'description': description
        }
        self.transactions.append(transaction)

    def get_exchange_rate(self, from_currency, to_currency):
        """Fetch current exchange rate"""
        url = f"https://api.exchangerate-api.com/v4/latest/{from_currency}"
        try:
            response = requests.get(url, timeout=5)
            response.raise_for_status()
            rates = response.json()['rates']
            return rates.get(to_currency, 1.0)
        except:
            return 1.0  # Fallback

    def analyze_spending(self):
        """Analyze spending patterns"""
        if not self.transactions:
            print("No transactions to analyze")
            return
        
        # Convert to DataFrame
        df = pd.DataFrame(self.transactions)
        
        # Basic statistics
        total_spent = df['amount'].sum()
        avg_transaction = df['amount'].mean()
        
        print(f"Total spent: ${total_spent:.2f}")
        print(f"Average transaction: ${avg_transaction:.2f}")
        print(f"Number of transactions: {len(df)}")
        
        # Category breakdown
        category_totals = df.groupby('category')['amount'].sum().sort_values(ascending=False)
        print(f"\nSpending by category:")
        for category, amount in category_totals.items():
            print(f"  {category}: ${amount:.2f}")
        
        return df, category_totals

    def visualize_spending(self):
        """Create spending visualizations"""
        df, category_totals = self.analyze_spending()
        
        if df is None:
            return
        
        # Create plots
        fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(15, 6))
        
        # Pie chart of categories
        ax1.pie(category_totals.values, labels=category_totals.index, autopct='%1.1f%%')
        ax1.set_title('Spending by Category')
        
        # Timeline of spending
        df['date'] = pd.to_datetime(df['date'])
        daily_spending = df.groupby('date')['amount'].sum()
        ax2.plot(daily_spending.index, daily_spending.values, marker='o')
        ax2.set_title('Daily Spending')
        ax2.set_xlabel('Date')
        ax2.set_ylabel('Amount ($)')
        ax2.tick_params(axis='x', rotation=45)
        
        plt.tight_layout()
        plt.show()

# Usage example
tracker = FinanceTracker()

# Add some sample transactions
tracker.add_transaction(50.00, 'Food', 'Grocery shopping', datetime(2024, 1, 15).date())
tracker.add_transaction(1200.00, 'Rent', 'Monthly rent', datetime(2024, 1, 1).date())
tracker.add_transaction(25.00, 'Food', 'Restaurant dinner', datetime(2024, 1, 20).date())
tracker.add_transaction(100.00, 'Utilities', 'Electric bill', datetime(2024, 1, 10).date())
tracker.add_transaction(30.00, 'Transportation', 'Gas', datetime(2024, 1, 18).date())

# Analyze and visualize
print("=== Personal Finance Analysis ===")
tracker.analyze_spending()
tracker.visualize_spending()

# Bonus: Currency conversion
usd_to_eur = tracker.get_exchange_rate('USD', 'EUR')
print(f"\nExchange rate USD to EUR: {usd_to_eur:.4f}")
→ This page was created with help from Claude AI.