Python Code
Samples
Medium snippets you can copy, study, and run in the browser editor.
Create a Python Tool That Generates Professional Excel Dashboards
Generate a professional sales dashboard in an Excel workbook with styled headers, a bar chart, and formatted number cells using the openpyxl library.
import openpyxl
from openpyxl.chart import BarChart, Reference
from openpyxl.styles import Font, PatternFill, Alignment, Border, Side
from openpyxl.utils import get_column_letter
def create_sales_dashboard(workbook_path: str) -> None:
"""Generate a professional sales dashboard in an Excel workbook."""
wb = op…
Generate a Beautiful Folder Tree Visualization in Python
A Python utility that creates a visual tree of a directory structure, excluding common files, with configurable depth.
import os
from pathlib import Path
class FolderTree:
def __init__(self, root_path=".", ignore_list=None, max_depth=3):
self.root = Path(root_path)
self.ignore = set(ignore_list or [".git", "__pycache__", ".DS_Store"])
self.max_depth = max_depth
def generate(self):
tree…
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 Generate Beautiful QR Codes with Embedded Logos in Python
Generate a high-error-correction QR code and paste a logo image in the center to create a branded, scannable QR code.
import qrcode
from PIL import Image
def generate_qr_with_logo(data, logo_path, output_path):
qr = qrcode.QRCode(
version=1,
error_correction=qrcode.constants.ERROR_CORRECT_H,
box_size=10,
border=4,
)
qr.add_data(data)
qr.make(fit=True)
qr_img = qr.make_image(fill_c…
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 Generate a Power Set in Python with Bitmasks
Generate the power set of a small list using a bitmask approach, producing all possible subsets.
def power_set(items):
"""Generate the power set of a list using bitmask approach."""
n = len(items)
result = []
for mask in range(1 << n):
subset = []
for i in range(n):
if mask & (1 << i):
subset.append(items[i])
result.append(subset)
r…
How to Generate Primes with a Generator in Python
Generate prime numbers up to a limit using the Sieve of Eratosthenes wrapped in a generator expression for lazy evaluation.
def prime_generator(limit):
sieve = [True] * (limit + 1)
sieve[0] = sieve[1] = False
for i in range(2, int(limit ** 0.5) + 1):
if sieve[i]:
for j in range(i * i, limit + 1, i):
sieve[j] = False
return (num for num, is_prime in enumerate(sieve) if is_prime)
if __n…
Automatically Generate Charts from CSV Files with One Command
Read a CSV file with headers, extract the first two numeric columns, and save a matplotlib line chart as a PNG image.
import csv
import sys
from pathlib import Path
import matplotlib.pyplot as plt
def generate_chart(csv_path: str) -> None:
"""Read a CSV file with headers and plot the first two numeric columns."""
data = []
with open(csv_path, 'r', newline='') as f:
reader = csv.reader(f)
headers = next(re…
Build a Complete Website Sitemap Generator Without External Services
Crawl a website recursively using only Python's standard library to generate a structured sitemap of internal links.
import json
from urllib.parse import urlparse, urljoin
from collections import deque
import urllib.request
import urllib.error
import re
from html.parser import HTMLParser
class SitemapParser(HTMLParser):
def __init__(self, base_url):
super().__init__()
self.base_url = base_url
self.links …
Build an RSS feed from markdown blog posts in Python
Scans a folder of markdown files, extracts titles, dates, and excerpts, and generates a valid RSS 2.0 XML feed.
import re
from pathlib import Path
from xml.etree.ElementTree import Element, SubElement, tostring
from datetime import datetime, timezone
from xml.dom import minidom
def build_rss(blog_dir, site_url="https://example.com"):
feed = Element("rss", version="2.0")
channel = SubElement(feed, "channel")
SubElem…
Generate Beautiful Project Documentation from Python Source Code Automatically
Automatically generate a markdown summary of function docstrings from any Python source file using the AST module.
import ast
import inspect
from pathlib import Path
def extract_docstrings_from_file(filepath):
"""Parse a Python file and collect function docstrings."""
source = Path(filepath).read_text()
tree = ast.parse(source)
docs = []
for node in ast.walk(tree):
if isinstance(node, (ast.FunctionDef…
Generate Holiday Calendars for Different Countries in Python
Generate a sorted list of public holidays for a given country and year using Python's calendar and datetime modules.
import calendar
from datetime import date, timedelta
def generate_holiday_calendar(country_code, year=2025):
holidays = []
if country_code == "US":
# New Year's Day
holidays.append(date(year, 1, 1))
# Independence Day
holidays.append(date(year, 7, 4))
# Thanksgivin…
Generate Strong SSH Keys and Save Them Securely with Python
Generate a 4096-bit RSA SSH key pair using Python's cryptography library and save both private and public keys with restricted file permissions.
import os
import stat
from pathlib import Path
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric import rsa
from cryptography.hazmat.backends import default_backend
def generate_ssh_keypair(key_path: str = "id_rsa", passphrase: str = None):
"""Generate a 4096-…
How to Generate Project Statistics Including Lines of Code and Complexity in Python
Walk through a Python script that scans a project directory for Python files, counts lines of code excluding blanks and comments, and estimates cyclomatic complexity by counting decision keywords.
import os
from pathlib import Path
def count_lines_of_code(filepath):
"""Counts lines of code in a Python file, excluding blank lines and comments."""
try:
with open(filepath, 'r') as f:
lines = f.readlines()
code_lines = [line for line in lines if line.strip() and not line.strip()…
How to Generate a Dependency Graph for Python Projects
This script walks through a Python project directory, parses each .py file's imports, and prints a dependency graph showing which modules depend on which other modules.
import os
import ast
from pathlib import Path
from collections import defaultdict
def get_imports(filepath):
with open(filepath) as f:
try:
tree = ast.parse(f.read())
except SyntaxError:
return []
imports = []
for node in ast.walk(tree):
if isinstance(node, …
Generate CHANGELOG from Conventional Commits in Python
Parse your git log for conventional commits (feat, fix) and produce a simple Markdown CHANGELOG with grouped features and bug fixes.
import subprocess
import re
import sys
from collections import OrderedDict
CONVENTIONAL_COMMIT = re.compile(
r"^(?P<type>feat|fix|chore|docs|refactor|perf|test|build|ci|style)(?:\((?P<scope>[^)]+)\))?: (?P<description>.+)"
)
def get_git_log():
return subprocess.run(
["git", "log", "--format=%s"],
…
Generate Release Notes Markdown from PR Titles in Python
Generate structured Markdown release notes from a list of pull request titles using conventional commit types.
import json
from datetime import datetime, timezone
PRS = [
{"title": "feat: add user login", "number": 12, "merged_at": "2025-01-10"},
{"title": "fix: resolve payment timeout", "number": 13, "merged_at": "2025-01-11"},
{"title": "chore: bump dependencies", "number": 14, "merged_at": "2025-01-12"},
{"…
How to Format Git Patch Series as an MBOX File in Python
Generate a patch-series mbox file from commit metadata with numbered [PATCH nnn/nnn] subjects and a Git-style footer.
import re
from pathlib import Path
def format_patch_series_mbox(commits, output_path="series.mbox"):
entries = []
for idx, commit in enumerate(commits, start=1):
subject = commit["subject"]
author = commit["author"]
email = commit["email"]
date = commit["date"]
body = …
How to Generate Release Notes from Git Commit Messages in Python
This script fetches recent Git commit messages using conventional commit prefixes (feat, fix, etc.), categorizes them, and prints formatted release notes with today's date.
import subprocess
import re
from datetime import datetime
def get_git_log(since_tag="HEAD~10", format_str="%s"):
"""Retrieve commit messages from git log."""
try:
result = subprocess.run(
["git", "log", f"--since={since_tag}", f"--format={format_str}"],
capture_output=True,
…
How to generate and parse an interactive rebase TODO list in Python
Generate a Git interactive rebase TODO list from commit data and parse it back into structured records.
import re
from collections import namedtuple
Commit = namedtuple("Commit", ["hash", "subject"])
def generate_rebase_todo(commits, action="pick"):
todo_lines = []
for i, commit in enumerate(commits):
if i == 0 and action == "reword":
todo_lines.append(f"reword {commit.hash} {commit.subject…
Generate a Mock Presigned URL in Python with HMAC
Build a mock AWS S3 presigned URL using an HMAC-SHA256 signature, mimicking the core SigV4 pattern without cloud SDK dependencies.
import hashlib
import hmac
import time
import base64
def generate_presigned_url_mock(secret_key, bucket, object_key, expires_in=3600):
# Build the canonical request string (simplified AWS SigV4 style)
timestamp = str(int(time.time()))
expiry = str(int(time.time()) + expires_in)
payload = f"GET\n/{buck…
Build a Python Performance Profiler That Generates Readable Reports
Use cProfile and pstats to profile Python functions and print a sorted performance report showing the top time-consuming calls.
import cProfile
import pstats
import io
from pathlib import Path
def slow_function():
total = 0
for i in range(500_000):
total += i ** 2
return total
def fast_function():
total = sum(i * i for i in range(500_000))
return total
def profile_functions():
profiler = cProfile.Profile()
…
How to Build a Producer-Consumer Pattern with asyncio.Queue in Python
This code implements a classic producer-consumer pattern using asyncio.Queue to coordinate one producer task that generates items and two consumer tasks that process them concurrently, with a sentinel value to signal completion.
import asyncio
import random
async def producer(queue, item_count):
for i in range(item_count):
item = random.randint(1, 100)
await queue.put(item)
print(f"Produced: {item}")
await asyncio.sleep(0.1)
await queue.put(None) # Sentinel to signal end
async def consumer(queue, n…
How to Use Hypothesis Strategies for Lists of Text in Python
Generate random lists of non-empty strings with Hypothesis and verify that joining them with a comma-and-space separator meets expected length and containment invariants.
from hypothesis import given, strategies as st
from hypothesis import example
@given(st.lists(st.text(min_size=1, max_size=10), min_size=1, max_size=5))
def test_joined_string_length(items):
"""Each text is non-empty; a joined string should be at least as long
as the number of items (separator adds character…
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.