Python Code
Samples
Easy snippets you can copy, study, and run in the browser editor.
How to Build a Text Processor in Python
This code defines functions to count words, sentences, and find the longest word in a text, then prints basic statistics like uppercase and lowercase versions.
def count_words(text):
return len(text.split())
def count_sentences(text):
sentence_endings = ".!?"
count = 0
for char in text:
if char in sentence_endings:
count += 1
return count
def longest_word(text):
words = text.split()
if not words:
return ""
retur…
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 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…
Handle ValueError and ZeroDivisionError in Python with try except
Learn how to catch ValueError and ZeroDivisionError in Python with a practical safe_divide function and demonstrate error handling for invalid conversions.
def safe_divide(numerator, denominator):
try:
result = numerator / denominator
except ValueError as e:
print(f"ValueError caught: {e}")
return None
except ZeroDivisionError:
print("Cannot divide by zero!")
return None
return result
# Test cases
print(safe_divide…
How to Convert Data Types in Python with a Helper Class
This code defines a beginner-friendly OOP helper class for common data conversions like string to list, list to dict, JSON string, and CSV row, with an advanced subclass for numeric casting.
class DataConverter:
"""A beginner-friendly helper class for common data conversions."""
def __init__(self, data):
self.data = data
def to_list(self):
"""Convert string data (comma-separated) to a list."""
if isinstance(self.data, str):
return [item.strip() for…
How to Implement Iterator Protocol on a Custom Class in Python
Create a custom iterable class by defining the __iter__ and __next__ methods, enabling use in for loops and list conversions.
class Countdown:
"""Iterator that counts down from start to 0."""
def __init__(self, start):
self.start = start
self.current = start
def __iter__(self):
return self
def __next__(self):
if self.current < 0:
raise StopIteration
value = self.current
…
How to Build a Docker Image Tag Script in Python
Generate consistent Docker image tags from service names and versions with automatic normalization.
#!/usr/bin/env python3
"""Mock script for building docker image tags."""
def build_tag(service_name: str, version: str, registry: str = "docker.io") -> str:
"""Construct a docker image tag."""
safe_name = service_name.lower().replace("_", "-")
return f"{registry}/{safe_name}:{version}"
if __name__ == "…
How to Generate an Inventory CSV of Installed pip Packages in Python
This script uses subprocess and csv to list all installed pip packages and write their names and versions into a CSV inventory file.
import subprocess
import csv
def get_installed_packages():
"""Return a list of (name, version) tuples for installed pip packages."""
result = subprocess.run(
["pip", "list", "--format=freeze"],
capture_output=True,
text=True,
check=True
)
packages = []
for line in r…
Pin Python package versions in requirements.txt
Pin package versions in requirements.txt-style text by adding ==version when no specifier is present, while preserving existing version constraints and comments.
import re
from pathlib import Path
def pin_versions(requirements_text: str) -> str:
"""
Pin package versions in requirements.txt-style text.
Adds ==version if no version specifier is present.
Keeps existing specifiers (>=, <=, ~=, etc.) unchanged.
"""
lines = requirements_text.strip().splitli…
Mock GCP Secret Manager access version in Python
A minimal mock of GCP Secret Manager that stores secret versions, retrieves payloads by version, and logs access timestamps.
import json
import time
from datetime import datetime, timezone
class MockSecretManager:
"""Minimal mock of GCP Secret Manager access/version behavior."""
def __init__(self):
self._secrets = {}
self._access_log = []
def create_secret(self, secret_id: str, payload: str) -> dict:
…
Mock pip-compile to Resolve Requirements in Python
A mock function that mimics pip-compile by converting a requirements.in file into pinned, locked package versions.
import subprocess
import tempfile
from pathlib import Path
def compile_requirements_mock(requirements_in: str) -> str:
"""Mock pip-compile: resolve a simple requirements.in into a locked format."""
lines = [line.strip() for line in requirements_in.splitlines() if line.strip() and not line.startswith("#")]
…
How to Mock Service Versioning URI in Python
Run a minimal HTTP server in Python that routes requests to different versions of a service URI like /v1/users vs /v2/users.
from http.server import HTTPServer, BaseHTTPRequestHandler
import json
class VersionedHandler(BaseHTTPRequestHandler):
def _send_json(self, payload, status=200):
body = json.dumps(payload).encode("utf-8")
self.send_response(status)
self.send_header("Content-Type", "application/json")
…
How to implement a canary traffic split in Python
Route incoming traffic between stable and canary model or service versions using a weight-based random split with deterministic testing.
import random
def canary_route(service_name: str, canary_weight: float = 0.2) -> str:
"""Route traffic between stable and canary versions based on weight."""
rng = random.Random(42) # deterministic for reproducible demo
if rng.random() < canary_weight:
return f"{service_name}-canary"
return …
Model registry version mock in Python
A simple in-memory model registry that stores model versions with metadata and supports version listing and latest retrieval.
class ModelRegistry:
def __init__(self):
self.models = {}
def register(self, name, version, model_type, metrics=None):
if name not in self.models:
self.models[name] = []
entry = {
"version": version,
"model_type": model_type,
"metrics": m…
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.