Intermediate

Working with Python Libraries

Leverage Python's vast ecosystem to build powerful applications

Python's true power lies in its vast ecosystem of libraries and packages. With over 400,000 packages available on PyPI (Python Package Index), you can find tools for virtually any task - from web development to data science, machine learning to automation.

Learning to work with external libraries, manage dependencies, and create virtual environments is essential for professional Python development.

πŸ“š What You'll Learn

  • Understanding pip - Python's package manager
  • Installing and managing packages
  • Creating and using virtual environments
  • Managing dependencies with requirements.txt
  • Popular Python libraries and their uses
  • Working with the datetime module
  • Making HTTP requests with requests library
  • Best practices for project setup

1. Understanding pip

pip is Python's package installer. It downloads and installs packages from PyPI (Python Package Index).

Basic pip Commands

# Check pip version
pip --version

# Install a package
pip install requests

# Install specific version
pip install requests==2.28.0

# Install minimum version
pip install requests>=2.25.0

# Upgrade a package
pip install --upgrade requests

# Uninstall a package
pip uninstall requests

# List installed packages
pip list

# Show package details
pip show requests

# Search for packages (deprecated, use pypi.org)
# pip search machine-learning

Installing Multiple Packages

# Install multiple packages at once
pip install requests pandas numpy

# Install from requirements file
pip install -r requirements.txt

2. Virtual Environments

Virtual environments create isolated Python installations for each project, preventing dependency conflicts.

⚠️ Why Virtual Environments?
Without virtual environments, all packages install globally. Project A might need Django 3.0 while Project B needs Django 4.0. Virtual environments solve this by keeping each project's dependencies separate.

Creating Virtual Environments

# Create a virtual environment
python -m venv myenv

# Or using a specific Python version
python3.11 -m venv myenv

# Activate the virtual environment

# On macOS/Linux:
source myenv/bin/activate

# On Windows:
myenv\Scripts\activate

# Your prompt changes to show the active environment:
(myenv) $

# Install packages (now only in this environment)
pip install requests pandas

# Deactivate when done
deactivate

Project Structure with Virtual Environment

my_project/
β”œβ”€β”€ venv/                  # Virtual environment (don't commit to git)
β”œβ”€β”€ src/                   # Source code
β”‚   β”œβ”€β”€ __init__.py
β”‚   └── main.py
β”œβ”€β”€ tests/                 # Test files
β”œβ”€β”€ requirements.txt       # Dependencies
β”œβ”€β”€ .gitignore            # Ignore venv, __pycache__, etc.
└── README.md             # Project documentation

3. Managing Dependencies

requirements.txt

The requirements.txt file lists all project dependencies, making it easy to recreate the environment.

# Generate requirements.txt from current environment
pip freeze > requirements.txt

# Install from requirements.txt
pip install -r requirements.txt

Example requirements.txt

# Web framework
flask==2.3.0

# HTTP requests
requests>=2.28.0

# Data manipulation
pandas==2.0.0
numpy==1.24.0

# Database
sqlalchemy==2.0.0

# Environment variables
python-dotenv==1.0.0
πŸ’‘ Best Practice: Use version pinning (==) for production to ensure consistency. Use minimum versions (>=) for libraries during development.

4. Popular Python Libraries

By Category

🌐 Web Development

  • Flask - Lightweight web framework
  • Django - Full-featured web framework
  • FastAPI - Modern, fast API framework

πŸ“Š Data Science

  • pandas - Data manipulation and analysis
  • numpy - Numerical computing
  • matplotlib - Data visualization
  • scikit-learn - Machine learning

πŸ€– AI/Machine Learning

  • tensorflow - Deep learning framework
  • pytorch - Deep learning framework
  • transformers - NLP models

πŸ”§ Utilities

  • requests - HTTP library
  • beautifulsoup4 - Web scraping
  • pillow - Image processing
  • pytest - Testing framework

5. Working with datetime Module

The datetime module (built-in) provides classes for working with dates and times.

from datetime import datetime, date, time, timedelta

# Current date and time
now = datetime.now()
print(now)  # 2025-10-29 14:30:45.123456

today = date.today()
print(today)  # 2025-10-29

# Create specific dates
birthday = date(1990, 5, 15)
meeting = datetime(2025, 10, 30, 14, 30)  # Oct 30, 2025 at 2:30 PM

# Format dates
formatted = now.strftime("%Y-%m-%d %H:%M:%S")
print(formatted)  # 2025-10-29 14:30:45

formatted2 = now.strftime("%B %d, %Y")
print(formatted2)  # October 29, 2025

# Parse strings to dates
date_string = "2025-10-29"
parsed = datetime.strptime(date_string, "%Y-%m-%d")

# Date arithmetic with timedelta
tomorrow = today + timedelta(days=1)
next_week = today + timedelta(weeks=1)
three_hours_ago = now - timedelta(hours=3)

# Calculate difference
age = today - birthday
print(f"Days old: {age.days}")

# Compare dates
if meeting > now:
    print("Meeting is in the future")

# Practical example: Calculate project deadline
def get_deadline(start_date, duration_days):
    """Calculate project deadline excluding weekends."""
    current_date = start_date
    days_added = 0
    
    while days_added < duration_days:
        current_date += timedelta(days=1)
        # Skip weekends (5=Saturday, 6=Sunday)
        if current_date.weekday() < 5:
            days_added += 1
    
    return current_date

project_start = date(2025, 10, 29)
deadline = get_deadline(project_start, 20)  # 20 business days
print(f"Deadline: {deadline}")

# Working with time zones (requires pytz)
# pip install pytz
import pytz

utc = pytz.UTC
eastern = pytz.timezone('US/Eastern')

utc_now = datetime.now(utc)
eastern_now = utc_now.astimezone(eastern)
print(f"UTC: {utc_now}")
print(f"Eastern: {eastern_now}")

6. Working with requests Library

The requests library makes HTTP requests simple and elegant.

# Install requests
pip install requests
import requests

# GET request
response = requests.get('https://api.github.com')
print(response.status_code)  # 200
print(response.json())       # Parse JSON response

# GET with parameters
params = {'q': 'python', 'sort': 'stars'}
response = requests.get('https://api.github.com/search/repositories', params=params)
data = response.json()

# POST request
payload = {'username': 'alice', 'email': 'alice@example.com'}
response = requests.post('https://httpbin.org/post', json=payload)

# Headers
headers = {'Authorization': 'Bearer YOUR_TOKEN'}
response = requests.get('https://api.example.com/data', headers=headers)

# Handling errors
try:
    response = requests.get('https://api.example.com/data', timeout=5)
    response.raise_for_status()  # Raises HTTPError for bad status
    data = response.json()
except requests.exceptions.Timeout:
    print("Request timed out")
except requests.exceptions.HTTPError as e:
    print(f"HTTP error: {e}")
except requests.exceptions.RequestException as e:
    print(f"Error: {e}")

# Practical example: Weather API client
class WeatherAPI:
    """Simple weather API client."""
    
    def __init__(self, api_key):
        self.api_key = api_key
        self.base_url = "https://api.openweathermap.org/data/2.5"
    
    def get_current_weather(self, city):
        """Get current weather for a city."""
        endpoint = f"{self.base_url}/weather"
        params = {
            'q': city,
            'appid': self.api_key,
            'units': 'metric'
        }
        
        try:
            response = requests.get(endpoint, params=params, timeout=10)
            response.raise_for_status()
            data = response.json()
            
            return {
                'city': data['name'],
                'temperature': data['main']['temp'],
                'description': data['weather'][0]['description'],
                'humidity': data['main']['humidity']
            }
        except requests.exceptions.RequestException as e:
            print(f"Error fetching weather: {e}")
            return None
    
    def get_forecast(self, city, days=5):
        """Get weather forecast."""
        endpoint = f"{self.base_url}/forecast"
        params = {
            'q': city,
            'appid': self.api_key,
            'units': 'metric',
            'cnt': days * 8  # 8 forecasts per day
        }
        
        response = requests.get(endpoint, params=params, timeout=10)
        response.raise_for_status()
        return response.json()

# Usage (requires API key from openweathermap.org)
# weather = WeatherAPI('YOUR_API_KEY')
# current = weather.get_current_weather('London')
# print(f"{current['city']}: {current['temperature']}Β°C, {current['description']}")

7. Practical Project: CLI Weather App

#!/usr/bin/env python3
"""
Simple weather CLI app using requests and datetime.

Install: pip install requests python-dotenv
Usage: python weather.py London
"""

import sys
import requests
from datetime import datetime
import os
from dotenv import load_dotenv

# Load environment variables from .env file
load_dotenv()

class WeatherApp:
    """Command-line weather application."""
    
    def __init__(self):
        self.api_key = os.getenv('WEATHER_API_KEY')
        if not self.api_key:
            print("Error: WEATHER_API_KEY not found in environment")
            sys.exit(1)
        
        self.base_url = "https://api.openweathermap.org/data/2.5/weather"
    
    def get_weather(self, city):
        """Fetch weather data for city."""
        params = {
            'q': city,
            'appid': self.api_key,
            'units': 'metric'
        }
        
        try:
            response = requests.get(self.base_url, params=params, timeout=10)
            response.raise_for_status()
            return response.json()
        except requests.exceptions.RequestException as e:
            print(f"Error: {e}")
            return None
    
    def display_weather(self, data):
        """Display weather information."""
        if not data:
            return
        
        # Parse data
        city = data['name']
        country = data['sys']['country']
        temp = data['main']['temp']
        feels_like = data['main']['feels_like']
        humidity = data['main']['humidity']
        description = data['weather'][0]['description'].title()
        wind_speed = data['wind']['speed']
        
        # Sunrise/sunset
        sunrise = datetime.fromtimestamp(data['sys']['sunrise'])
        sunset = datetime.fromtimestamp(data['sys']['sunset'])
        
        # Display
        print("\n" + "="*50)
        print(f"Weather in {city}, {country}")
        print("="*50)
        print(f"Temperature:    {temp}Β°C (feels like {feels_like}Β°C)")
        print(f"Conditions:     {description}")
        print(f"Humidity:       {humidity}%")
        print(f"Wind Speed:     {wind_speed} m/s")
        print(f"Sunrise:        {sunrise.strftime('%H:%M')}")
        print(f"Sunset:         {sunset.strftime('%H:%M')}")
        print("="*50 + "\n")
    
    def run(self, city):
        """Run the weather app."""
        print(f"Fetching weather for {city}...")
        data = self.get_weather(city)
        self.display_weather(data)

def main():
    """Main function."""
    if len(sys.argv) < 2:
        print("Usage: python weather.py CITY")
        print("Example: python weather.py London")
        sys.exit(1)
    
    city = ' '.join(sys.argv[1:])
    app = WeatherApp()
    app.run(city)

if __name__ == '__main__':
    main()

# Create .env file with:
# WEATHER_API_KEY=your_api_key_here

8. Best Practices

βœ… Package Management Best Practices

  • Always use virtual environments for projects
  • Pin versions in requirements.txt for production
  • Update regularly but test after updates
  • Use .gitignore to exclude venv/ and __pycache__/
  • Document dependencies and their purpose
  • Use environment variables for secrets (API keys)
  • Test with clean install from requirements.txt

Example .gitignore

# Python
__pycache__/
*.py[cod]
*$py.class
*.so
.Python

# Virtual environments
venv/
env/
ENV/

# Environment variables
.env
.env.local

# IDE
.vscode/
.idea/
*.swp

# OS
.DS_Store
Thumbs.db

Key Takeaways

βœ… What You've Learned

  • pip: Install, upgrade, and manage Python packages
  • Virtual Environments: Isolate project dependencies
  • requirements.txt: Document and share dependencies
  • Popular Libraries: Overview of Python's ecosystem
  • datetime: Work with dates and times
  • requests: Make HTTP requests easily
  • Best Practices: Professional project setup

πŸš€ Level Up: Production-Ready Python Tools

Accelerate your development with AI-powered coding and cloud notebooks

πŸ€–

GitHub Copilot - AI Pair Programmer

Price: $10/month (Free for students/teachers) | Perfect for: Writing code faster with AI suggestions

AI assistant that suggests entire lines or blocks of code as you type. Trained on billions of lines of public code, it understands context and helps you code 55% faster.

Game-changing features:

  • Autocomplete entire functions from comments or names
  • Get alternative solutions with one keystroke
  • Learn new libraries faster (sees how others use them)
  • Works in VS Code, PyCharm, Vim, and more
Try Copilot Free β†’
☁️

Google Colab Pro - Cloud Python Notebooks

Price: $9.99/month | Perfect for: Data science, ML projects, and sharing notebooks

Jupyter notebooks in the cloud with free GPU/TPU access. Pre-installed libraries (NumPy, Pandas, TensorFlow), shareable links, and Google Drive integration.

Why developers choose Colab Pro:

  • Free GPU for machine learning (Pro gives more runtime)
  • No setupβ€”all libraries pre-installed in cloud
  • Share notebooks like Google Docs (great for teaching)
  • Access from any device with a browser
Try Colab Pro β†’
πŸ“Š

Kaggle - Data Science Competitions & Learning

Price: 100% Free | Perfect for: Real-world data science practice & portfolio building

Practice Python with real datasets, compete in ML challenges, and learn from 15M+ data scientists. Build your portfolio with public notebooks and kaggle medals.

What makes Kaggle unique:

  • Free GPU/TPU access (30+ hrs/week)
  • 50,000+ public datasets to practice with
  • Competitions with real prizes ($10K-$1M)
  • Community of experts sharing solutions
Start Learning Free β†’

πŸ’‘ You've completed Python fundamentalsβ€”these tools help you build real projects faster and collaborate with the global developer community!

🎯 Congratulations!

You've completed the Python Fundamentals course! You now have:

  • βœ… Solid foundation in Python syntax and concepts
  • βœ… Experience with data structures and algorithms
  • βœ… Object-oriented programming skills
  • βœ… File handling and data processing abilities
  • βœ… Knowledge of Python's ecosystem and libraries

Next Steps: Apply these skills to AI/ML, web development, data science, or automation projects!

πŸ“ Knowledge Check

Test your understanding of Python libraries!

Question 1: Which library is used for numerical computing?

A) requests
B) numpy
C) beautifulsoup
D) flask

Question 2: Which library is used for data manipulation and analysis?

A) matplotlib
B) requests
C) pandas
D) django

Question 3: How do you install a Python library?

A) pip install library_name
B) python install library_name
C) import install library_name
D) download library_name

Question 4: Which library is used for making HTTP requests?

A) pandas
B) numpy
C) matplotlib
D) requests

Question 5: Which library is used for data visualization?

A) requests
B) matplotlib
C) flask
D) beautifulsoup
πŸŽ“

Get Your Completion Certificate

Showcase your Python skills! Add this certificate to your resume and LinkedIn profile.

πŸ“œ Your certificate includes:

  • βœ… Official Python Fundamentals completion
  • βœ… Unique verification ID
  • βœ… Shareable credential for job applications
  • βœ… Public verification page
  • βœ… Professional PDF certificate