Python Code
Samples
Copy-ready Python snippets by topic and difficulty — short, focused, and runnable in the browser editor.
How to Build a Data Helper for LLM Prompts in Python
A beginner-friendly helper class that flattens nested dictionaries, formats prompt templates, and safely parses JSON for AI/LLM pipelines.
import json
from typing import Any, Dict, List, Optional
class DataHelper:
"""Simple helper class for working with data in AI/LLM pipelines."""
def __init__(self, data: Optional[Dict[str, Any]] = None) -> None:
self.data = data or {}
def flatten(self, prefix: str = "") -> Dict[str, Any]…
How to Build a Simple Semantic Cache for Similar Prompts in Python
Mock a semantic cache that finds the closest matching prompt using word-overlap similarity and returns cached results above a threshold.
prompt_cache = [
"What is the capital of France?",
"How does recursion work?",
"Best practices for Python logging?",
"Explain binary search in one line.",
"How to reverse a string in Python?"
]
def normalize(text):
return " ".join(text.lower().split())
def similarity(a, b):
a_words = set(…
How to Log Prompts and Completions as JSONL Audit Files in Python
Read a JSONL file of LLM prompt–completion pairs, compute totals and averages, then write an audit summary with timestamps.
import json
from pathlib import Path
from datetime import datetime
def audit_jsonl(filepath):
logs = []
with open(filepath, encoding="utf-8") as f:
for line in f:
line = line.strip()
if not line:
continue
entry = json.loads(line)
logs.ap…
JSON Mode Prompt Schema Output in Python
Extract a user object to JSON with explicit schema keys, ready for LLM JSON-mode prompts.
import json
from typing import Any, Dict
def extract_user_as_json(user: Dict[str, Any]) -> str:
"""Extract a user object and return it as JSON using explicit schema keys."""
schema_fields = ("id", "name", "email", "is_active")
user_subset = {key: user[key] for key in schema_fields if key in user}
ret…
Serialize and Format Data for LLM Prompts in Python
Use dataclasses and the json module to convert Python objects to JSON strings, parse them back, and format structured data into prompt-friendly text for LLM calls.
import json
from dataclasses import dataclass, asdict
@dataclass
class Recipe:
"""Simple data model to represent a recipe."""
name: str
cuisine: str
prep_minutes: int
def to_json(recipe: Recipe) -> str:
"""Serialize a Recipe to a JSON string."""
return json.dumps(asdict(recipe), indent=2)
…
How to Create Interactive CLI Prompts in Python with questionary
Build mock interactive command-line prompts using questionary's select and text widgets with graceful handling of user cancellation.
import questionary
def main():
# Mock interactive prompts using questionary's select and text
choice = questionary.select(
"What is your favorite programming language?",
choices=["Python", "JavaScript", "Go", "Rust"]
).ask()
# ask() returns None if user cancels; handle gracefully
…
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.