Python Code
Samples
Copy-ready Python snippets by topic and difficulty — short, focused, and runnable in the browser editor.
How to Compare Two Strings in Python
Compares two string values and returns a detailed report with equality, case-insensitive comparison, lengths, and uppercase versions.
def compare_data(first_value, second_value):
"""Compare two string values and return a report."""
if first_value == second_value:
status = "MATCH"
else:
status = "DIFFER"
return {
"first_value": first_value,
"second_value": second_value,
"status": status,
…
How to Process Text Lines with Lists and Loops in Python
This code processes a list of text lines by stripping whitespace, converting to uppercase, and reporting character counts per line and totals.
def process_text(lines):
"""Convert a list of text lines to uppercase and report line statistics."""
processed = []
total_chars = 0
for index, line in enumerate(lines, start=1):
cleaned = line.strip().upper()
processed.append(cleaned)
total_chars += len(cleaned)
pri…
How to Process Text with Lists and Loops in Python
A beginner-friendly text processor that splits a sentence into words, filters by length, counts vowels, and reports results using lists and loops.
text = "Python makes text processing easy and fun"
words = text.lower().split()
print("Words in the sentence:")
for index, word in enumerate(words, start=1):
print(f"{index}. {word}")
filtered_words = [word for word in words if len(word) > 3]
print(f"\nWords longer than 3 characters: {filtered_words}")
letter…
How to Process Text with Lists and Loops in Python
Iterate over a list of text lines to count words, show uppercase versions, and report character counts per line.
# text_processor.py
def process_text(lines):
"""Count words, show uppercase, and count characters per line."""
total_words = 0
print("Line-by-line analysis:")
for i, line in enumerate(lines, start=1):
words = line.split()
total_words += len(words)
print(f" Line {i}: {len(words…
Profile Python functions with cProfile
Profile a Python program with cProfile, capture the stats in memory, and print a sorted performance report.
import cProfile
import pstats
import io
def slow_function():
total = 0
for i in range(100000):
total += i ** 2
return total
def medium_function():
return sum(range(10000))
def fast_function():
return sum(range(100))
def main():
result1 = slow_function()
result2 = medium_func…
How to Diff Two Dicts in Python for Config Drift
Recursively compare two dictionaries and report added, removed, and changed keys with their old and new values for debugging configuration drift.
def diff_dicts(a, b, path=""):
differences = []
for key in a.keys() | b.keys():
new_path = f"{path}.{key}" if path else key
if key not in a:
differences.append((new_path, "<missing>", b[key], "added"))
elif key not in b:
differences.append((new_path, a[key], "<…
Find Duplicate Web Pages by Content Similarity in Python
Compute SHA-256 hashes of file contents to detect and report duplicate HTML pages or any files in a directory.
import hashlib
import os
from collections import defaultdict
def get_file_hash(filepath):
"""Compute SHA-256 hash of file contents."""
sha256 = hashlib.sha256()
with open(filepath, 'rb') as f:
for chunk in iter(lambda: f.read(4096), b''):
sha256.update(chunk)
return sha256.hexdiges…
Generate Timesheet Reports from Daily Logs in Python
Aggregate daily log entries by project and produce a formatted timesheet report using Python's standard library.
import json
from pathlib import Path
from collections import defaultdict
def generate_timesheet_report(daily_logs: list[dict]) -> str:
"""
Generate a timesheet report from daily log entries.
Args:
daily_logs: List of dicts with 'date', 'project', 'hours', 'task' keys
Returns:
…
Generate a Monthly Calendar PDF in Python
Create a Python utility that generates a monthly calendar PDF using ReportLab, with weekday headers and day numbers laid out in a grid.
from calendar import TextCalendar
from datetime import datetime
from reportlab.lib.pagesizes import letter
from reportlab.pdfgen import canvas
import os
def generate_monthly_calendar_pdf(year, month, filename="calendar.pdf"):
cal = TextCalendar()
days = cal.monthdays2calendar(year, month)
month_name …
How to Audit Environment Variable Files for Missing Values in Python
A Python tool that reads an environment variable file and reports any variables with empty or missing values.
import os
import re
from pathlib import Path
def audit_env_file(filepath: str) -> None:
"""
Audit an environment variable file for missing values.
Prints file status and lists variables that have empty values.
"""
path = Path(filepath)
if not path.exists():
print(f"Error: File '{filepa…
How to Check Disk Free Space in Python with shutil.disk_usage
This Python script uses the standard library shutil.disk_usage to report total, used, and free disk space in bytes, plus a percentage usage figure.
import shutil
def check_disk_free_space(path="/"):
"""Return a tuple of total, used, and free disk space in bytes."""
usage = shutil.disk_usage(path)
return usage.total, usage.used, usage.free
if __name__ == "__main__":
total, used, free = check_disk_free_space()
print(f"Total: {total:,} bytes"…
How to Compare Directory Trees in Python
This code recursively scans two directory trees and reports files that exist in only one directory, as well as files present in both but with different content.
from pathlib import Path
def compare_directories(path1, path2):
dir1 = Path(path1)
dir2 = Path(path2)
if not dir1.is_dir() or not dir2.is_dir():
raise ValueError("Both paths must be directories.")
files1 = {p.relative_to(dir1) for p in dir1.rglob("*") if p.is_file()}
files2 = {p.relative…
How to Generate an Inventory Report of All Files in Python
Walk a directory tree, collect metadata for every file, and write a CSV inventory report using Python's os, pathlib, and csv modules.
import os
import csv
from pathlib import Path
from datetime import datetime
def generate_inventory_report(root_dir: str = "/", output_file: str = "inventory_report.csv"):
headers = ["File Path", "Size (bytes)", "Last Modified", "File Type"]
rows = []
start_time = datetime.now()
for dirpath, dirna…
How to Diff Two Dicts in Python: Added, Removed, and Changed Keys
Compare two dictionaries and report added, removed, and changed keys using Python's set operations on dict keys.
def diff_dicts(old: dict, new: dict) -> dict:
"""Compare two dicts and report added, removed, and changed keys."""
added = {k: new[k] for k in new.keys() - old.keys()}
removed = {k: old[k] for k in old.keys() - new.keys()}
common_keys = old.keys() & new.keys()
changed = {k: (old[k], new[k]) for k …
How to Validate JSON Types per Key in Python
Load a JSON object and validate the type of each key against an expected schema, reporting missing or mismatched fields.
import json
from typing import Any, Dict, Type
def validate_json_types(data: Dict[str, Any], schema: Dict[str, Type]) -> Dict[str, str]:
"""Validate that each key in data matches the expected type in schema."""
errors = {}
for key, expected_type in schema.items():
if key not in data:
e…
Automatically Generate Hardware Inventory Reports in Python
Generate a system hardware report including OS version, CPU cores, RAM, and disk usage using platform and psutil.
import platform
import psutil # requires: pip install psutil
from datetime import datetime
def generate_hardware_report():
report_lines = []
report_lines.append(f"Report Generated: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
report_lines.append(f"System: {platform.system()} {platform.release()} ({pl…
Build a Network Ping Monitor in Python
A Python script that continuously pings a remote host using subprocess and reports connectivity status with timestamps and latency.
import subprocess
import time
def ping_host(host, count=4):
"""Ping a host and return the results."""
try:
# Platform-independent ping command
cmd = ["ping", "-c", str(count), host]
result = subprocess.run(cmd, capture_output=True, text=True, timeout=10)
return result.stdout, r…
Convert HTML Tables to Excel Reports in Python
Convert HTML tables into formatted Excel reports using BeautifulSoup and Pandas with auto-adjusted column widths.
import pandas as pd
from bs4 import BeautifulSoup
from pathlib import Path
def html_table_to_excel(html_file: str, excel_file: str) -> None:
"""Convert HTML table to formatted Excel report."""
with open(html_file, 'r', encoding='utf-8') as f:
html_content = f.read()
soup = BeautifulSoup(html_…
Find Broken Image References Across a Website in Python
Crawl internal pages of a website, collect all image source URLs, then check each with HEAD requests to report any that return HTTP 4xx or connection errors.
import requests
from urllib.parse import urljoin, urlparse
from bs4 import BeautifulSoup
from concurrent.futures import ThreadPoolExecutor, as_completed
def find_all_links(base_url, max_pages=50):
visited, to_visit = set(), {base_url}
while to_visit and len(visited) < max_pages:
url = to_visit.pop()
…
Find Zombie Processes on Linux with Python
Parse the output of `ps -eo pid,stat,comm` to detect processes in zombie state (Z) on a Linux system and report their PIDs and commands.
#!/usr/bin/env python3
import os
import subprocess
def find_zombie_processes():
"""Find zombie processes (state 'Z') running on Linux."""
try:
result = subprocess.run(['ps', '-eo', 'pid,stat,comm'], capture_output=True, text=True, check=True)
zombies = []
for line in result.stdout.stri…
Find the Largest Files Consuming Disk Space with a Beautiful Terminal Report in Python
Scan a directory recursively and print a formatted terminal report of the largest files, with human-readable sizes.
import os
import sys
from pathlib import Path
def get_largest_files(directory: str, count: int = 10) -> list:
"""
Scan the given directory and return the largest files.
Args:
directory: Path to the directory to scan
count: Number of largest files to return
Returns:
…
Generate a Monthly Report CSV from Log Files in Python
Reads a CSV log file, filters events by a given month, aggregates daily event counts and revenue, and writes a summarized monthly report to a new CSV.
import csv
from collections import defaultdict
from datetime import datetime
def generate_monthly_report(log_file: str, month: str, output_file: str) -> None:
events_by_date = defaultdict(int)
revenue_by_date = defaultdict(float)
with open(log_file, 'r') as f:
for line in f:
date_…
How to Check SSL Certificate Expiry in Python
Connect to a host over TLS, extract the certificate's expiry date, and report days remaining using only the Python standard library.
import socket
import ssl
from datetime import datetime
def check_cert_expiry(hostname, port=443):
context = ssl.create_default_context()
with socket.create_connection((hostname, port), timeout=10) as sock:
with context.wrap_socket(sock, server_hostname=hostname) as tls_sock:
cert = tls_soc…
How to Map Network Drive Paths to Local Paths in Python
Convert mock SMB network drive paths (like 'S:\reports\q1.xlsx') to local placeholder paths and back using a simple mapping dictionary in Python.
"""Map mock SMB network drive paths to local placeholder paths."""
from dataclasses import dataclass
@dataclass(frozen=True)
class NetworkDrive:
letter: str
remote_path: str
DRIVES = {
"S:": NetworkDrive("S", r"\\server01\shares\sales"),
"M:": NetworkDrive("M", r"\\server02\media\movies"),
"X:": …
Browse by section
Each section groups closely related Python snippets.
Guide: free Python code samples library
Copy-ready Python snippets for learners and developers
PythonSkillset code samples are short, focused examples organised by topic and difficulty. Every snippet is server-rendered HTML — readable by search engines and easy to copy. Open any sample, read the notes, copy the code, then press Try in editor to run it in the browser with Pyodide.
How to use this library
- Pick a topic section — strings, lists, files, functions, and more
- Open a sample, read How it works, and copy the code block
- Run it in the IDE, tweak values, then take a related quiz or tutorial lesson
Samples vs tutorials and challenges
Samples are quick reference — one concept per page. For step-by-step teaching, use our Python tutorials. To test yourself, try quizzes or coding challenges. Clean up style with the Python formatter.