Python Programming Examples
Comprehensive Python code examples and tutorials covering fundamentals, data science, web development, automation, and advanced programming concepts.
Learning Paths
Choose your learning journey based on your goals and interests
Python Fundamentals
Master the core concepts of Python programming from basic syntax to object-oriented programming.
- Python Syntax & Basic Operations
- Data Types & Data Structures
- Control Flow & Functions
- Object-Oriented Programming
- Exception Handling
- File I/O & Module System
Data Science & Analytics
Learn Python for data analysis, visualization, and scientific computing with popular libraries.
- NumPy Arrays & Mathematical Operations
- Pandas DataFrames & Data Analysis
- Data Visualization with Matplotlib & Seaborn
- Jupyter Notebooks Best Practices
- Statistical Analysis & Modeling
- Data Cleaning & Preprocessing
Web Development
Build web applications, APIs, and handle web scraping with Python frameworks and libraries.
- Flask Web Applications & Templates
- Django Framework & MVT Pattern
- REST API Development & Authentication
- Web Scraping with BeautifulSoup & Requests
- Security & Authentication Patterns
Automation & Scripting
Automate repetitive tasks, manage files, and create powerful automation scripts.
- File System Operations & Management
- Web Automation with Selenium
- Email Automation & Notifications
- System Administration Scripts
Advanced Python
Explore advanced topics including async programming, concurrency, and machine learning.
- Async Programming with AsyncIO
- Multiprocessing & Threading
- Machine Learning with Scikit-learn
- Testing Frameworks & Debugging
Popular Python Examples
Data Analysis
import pandas as pd
import numpy as np
# Create a sample dataset
data = {
'Name': ['Alice', 'Bob', 'Charlie', 'Diana', 'Eve'],
'Age': [25, 30, 35, 28, 32],
'City': ['New York', 'London', 'Tokyo', 'Paris', 'Sydney'],
'Salary': [70000, 80000, 90000, 75000, 85000]
}
df = pd.DataFrame(data)
# Basic operations
print("Dataset Info:")
print(df.info())
# Statistical summary
print("\nStatistical Summary:")
print(df.describe())
# Group by city and calculate average salary
city_salary = df.groupby('City')['Salary'].mean()
print(f"\nAverage salary by city:\n{city_salary}")
# Filter data
high_earners = df[df['Salary'] > 80000]
print(f"\nHigh earners:\n{high_earners}")
# Add new calculated column
df['Salary_USD_K'] = df['Salary'] / 1000
print(f"\nWith salary in thousands:\n{df}")
import numpy as np
# Create arrays
arr1 = np.array([1, 2, 3, 4, 5])
arr2 = np.array([10, 20, 30, 40, 50])
# Array operations
print("Array 1:", arr1)
print("Array 2:", arr2)
print("Sum:", arr1 + arr2)
print("Product:", arr1 * arr2)
print("Dot product:", np.dot(arr1, arr2))
# Matrix operations
matrix_a = np.array([[1, 2], [3, 4]])
matrix_b = np.array([[5, 6], [7, 8]])
print("\nMatrix A:")
print(matrix_a)
print("Matrix B:")
print(matrix_b)
print("Matrix multiplication:")
print(np.matmul(matrix_a, matrix_b))
# Statistical operations
data = np.random.normal(100, 15, 1000) # 1000 samples, mean=100, std=15
print(f"\nGenerated data statistics:")
print(f"Mean: {np.mean(data):.2f}")
print(f"Standard deviation: {np.std(data):.2f}")
print(f"Min: {np.min(data):.2f}")
print(f"Max: {np.max(data):.2f}")
import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd
import numpy as np
# Create sample data
np.random.seed(42)
data = pd.DataFrame({
'x': np.random.randn(100),
'y': np.random.randn(100),
'category': np.random.choice(['A', 'B', 'C'], 100)
})
# Set up the plotting area
fig, axes = plt.subplots(2, 2, figsize=(12, 10))
fig.suptitle('Python Data Visualization Examples', fontsize=16)
# 1. Scatter plot
axes[0, 0].scatter(data['x'], data['y'], c=data['category'].astype('category').cat.codes, alpha=0.6)
axes[0, 0].set_title('Scatter Plot')
axes[0, 0].set_xlabel('X values')
axes[0, 0].set_ylabel('Y values')
# 2. Histogram
axes[0, 1].hist(data['x'], bins=20, alpha=0.7, color='skyblue')
axes[0, 1].set_title('Histogram')
axes[0, 1].set_xlabel('X values')
axes[0, 1].set_ylabel('Frequency')
# 3. Box plot
data.boxplot(column='y', by='category', ax=axes[1, 0])
axes[1, 0].set_title('Box Plot by Category')
# 4. Line plot
x_line = np.linspace(0, 10, 100)
y_line = np.sin(x_line)
axes[1, 1].plot(x_line, y_line, 'b-', linewidth=2)
axes[1, 1].set_title('Sine Wave')
axes[1, 1].set_xlabel('X')
axes[1, 1].set_ylabel('sin(X)')
plt.tight_layout()
plt.show()
Web Development
from flask import Flask, jsonify, request
from datetime import datetime
app = Flask(__name__)
# Sample data
books = [
{"id": 1, "title": "Python Cookbook", "author": "David Beazley"},
{"id": 2, "title": "Fluent Python", "author": "Luciano Ramalho"},
{"id": 3, "title": "Python Tricks", "author": "Dan Bader"}
]
@app.route('/')
def home():
return jsonify({
"message": "Welcome to Python Books API",
"timestamp": datetime.now().isoformat(),
"endpoints": ["/books", "/books/<id>"]
})
@app.route('/books', methods=['GET'])
def get_books():
return jsonify({"books": books})
@app.route('/books/<int:book_id>', methods=['GET'])
def get_book(book_id):
book = next((book for book in books if book["id"] == book_id), None)
if book:
return jsonify(book)
return jsonify({"error": "Book not found"}), 404
@app.route('/books', methods=['POST'])
def add_book():
data = request.get_json()
new_book = {
"id": len(books) + 1,
"title": data["title"],
"author": data["author"]
}
books.append(new_book)
return jsonify(new_book), 201
if __name__ == '__main__':
app.run(debug=True)
import requests
from bs4 import BeautifulSoup
import pandas as pd
import time
def scrape_quotes():
"""Scrape quotes from quotes.toscrape.com"""
quotes_data = []
base_url = "http://quotes.toscrape.com/page/{}"
for page in range(1, 4): # Scrape first 3 pages
url = base_url.format(page)
response = requests.get(url)
if response.status_code == 200:
soup = BeautifulSoup(response.content, 'html.parser')
quotes = soup.find_all('div', class_='quote')
for quote in quotes:
text = quote.find('span', class_='text').text
author = quote.find('small', class_='author').text
tags = [tag.text for tag in quote.find_all('a', class_='tag')]
quotes_data.append({
'quote': text,
'author': author,
'tags': ', '.join(tags)
})
# Be respectful - add delay between requests
time.sleep(1)
return quotes_data
# Scrape and save data
quotes = scrape_quotes()
df = pd.DataFrame(quotes)
print(f"Scraped {len(quotes)} quotes")
print(df.head())
# Save to CSV
df.to_csv('quotes.csv', index=False)
print("Data saved to quotes.csv")
import requests
import json
# 1. Simple GET request
def get_user_info(username):
"""Get GitHub user information"""
url = f"https://api.github.com/users/{username}"
response = requests.get(url)
if response.status_code == 200:
return response.json()
else:
return {"error": f"User {username} not found"}
# 2. POST request with authentication
def create_gist(token, description, files):
"""Create a GitHub gist"""
url = "https://api.github.com/gists"
headers = {
"Authorization": f"token {token}",
"Accept": "application/vnd.github.v3+json"
}
data = {
"description": description,
"public": True,
"files": files
}
response = requests.post(url, headers=headers, json=data)
return response.json()
# 3. Handle different response types
def fetch_json_data(url):
"""Fetch and handle JSON data with error handling"""
try:
response = requests.get(url, timeout=10)
response.raise_for_status() # Raises HTTPError for bad responses
return {
"success": True,
"data": response.json(),
"status_code": response.status_code
}
except requests.exceptions.Timeout:
return {"success": False, "error": "Request timed out"}
except requests.exceptions.HTTPError as e:
return {"success": False, "error": f"HTTP Error: {e}"}
except requests.exceptions.RequestException as e:
return {"success": False, "error": f"Request failed: {e}"}
# Example usage
user_data = get_user_info("octocat")
print(json.dumps(user_data, indent=2))
Python Ecosystem
Core Python
Master the fundamentals of Python programming language, syntax, and built-in libraries.
Data Science
Analyze data, create visualizations, and build machine learning models with powerful libraries.
Web Development
Build robust web applications, APIs, and handle web interactions with modern frameworks.
Automation
Automate repetitive tasks, manage systems, and create efficient workflows.
AI & Machine Learning
Build intelligent applications with machine learning and artificial intelligence frameworks.
DevOps & Deployment
Deploy applications, manage infrastructure, and implement CI/CD pipelines.
Why Learn Python?
High Demand
Python consistently ranks as one of the most popular and in-demand programming languages worldwide.
Versatile
Use Python for web development, data science, automation, AI, scientific computing, and more.
Large Community
Benefit from extensive libraries, frameworks, and a supportive global community of developers.
Easy to Learn
Clean, readable syntax makes Python an excellent choice for beginners and experienced developers.
Industry Standard
Used by tech giants like Google, Netflix, Instagram, and countless startups and enterprises.
Rapid Development
Build prototypes quickly and scale to production with Python's rich ecosystem and frameworks.