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.
pip is Python's package installer. It downloads and installs packages from PyPI (Python Package Index).
# 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
# Install multiple packages at once
pip install requests pandas numpy
# Install from requirements file
pip install -r requirements.txt
Virtual environments create isolated Python installations for each project, preventing dependency conflicts.
# 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
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
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
# 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
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}")
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']}")
#!/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
# 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
Accelerate your development with AI-powered coding and cloud notebooks
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:
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:
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:
π‘ You've completed Python fundamentalsβthese tools help you build real projects faster and collaborate with the global developer community!
You've completed the Python Fundamentals course! You now have:
Next Steps: Apply these skills to AI/ML, web development, data science, or automation projects!
Test your understanding of Python libraries!
Showcase your Python skills! Add this certificate to your resume and LinkedIn profile.