Python Code
Samples
Copy-ready Python snippets by topic and difficulty — short, focused, and runnable in the browser editor.
How to Count Word Frequencies in Python with Counter and Sets
This code processes a text string by lowercasing, splitting into words, counting frequencies with Counter, and extracting unique and sorted word lists using sets.
from collections import Counter
def process_text(text):
words = text.lower().split()
word_counts = Counter(words)
unique_words = set(words)
sorted_words = sorted(unique_words)
return {
"total_words": len(words),
"unique_words": len(unique_words),
"word_frequencies": di…
How to Count Words and Find Common Words in Python with Dictionaries and Sets
Build a simple text processor that counts unique words with dictionaries and finds common words across text halves using sets.
def process_text(text):
"""Process text: count unique words with counts, find common words."""
words = text.lower().replace(",", "").replace(".", "").split()
word_counts = {}
for word in words:
word_counts[word] = word_counts.get(word, 0) + 1
total_words = len(words)
unique_wo…
How to Remove Banned Words from a Set in Python
Filter a vocabulary set by removing banned words using the .difference() method.
vocabulary = {"apple", "banana", "cherry", "date", "elderberry"}
banned_words = {"banana", "date", "fig"}
# Remove banned words using set difference
allowed_words = vocabulary.difference(banned_words)
print("Original vocabulary:", sorted(vocabulary))
print("Banned words:", sorted(banned_words))
print("Allowed words …
How to Use Dictionaries and Sets in Python for Beginners
Introduces Python dictionaries and sets with practical examples including creating, modifying, and performing set operations, plus a word-frequency counter.
def demonstrate_dict_sets():
# Create a dictionary with basic info
person = {
"name": "Alice",
"age": 30,
"city": "New York"
}
print("Dictionary:", person)
# Access and modify dictionary values
person["age"] = 31
person["email"] = "alice@example.com"
print("Afte…
How to Use defaultdict(list) to Group Words by First Letter in Python
This code groups a list of words by their first letter using a defaultdict with a list factory, then prints each group sorted by initial.
from collections import defaultdict
def group_by_initial(words):
groups = defaultdict(list)
for word in words:
groups[word[0].upper()].append(word)
return dict(groups)
if __name__ == "__main__":
words = ["apple", "banana", "apricot", "blueberry", "cherry"]
result = group_by_initial(words)…
How to Validate Text and Count Words in Python
Count word frequencies, find unique and repeated words in a text using Python dictionaries and sets for beginner text validation.
def validate_text(text):
words = text.lower().split()
word_counts = {}
for word in words:
cleaned = word.strip('.,!?;:"\'')
if cleaned:
word_counts[cleaned] = word_counts.get(cleaned, 0) + 1
unique_words = set(word_counts.keys())
repeated_words = {word for word…
How to count words and find unique words in Python
Build a beginner-friendly text processor that counts word frequencies, finds unique words, and identifies words with vowels using dictionaries and sets.
def text_processor(text):
words = text.lower().replace(",", "").replace(".", "").split()
word_count = {}
for word in words:
word_count[word] = word_count.get(word, 0) + 1
unique_words = set(words)
vowels = set("aeiou")
words_with_vowels = {word for word in unique_words if vowe…
Text Processor with Dictionaries and Sets in Python
Build a simple text processor that counts word frequencies with a dictionary and tracks unique words with a set.
def analyze_text(text):
words = text.lower().split()
word_freq = {}
unique_words = set()
for word in words:
clean_word = word.strip('.,!?;:')
if clean_word:
word_freq[clean_word] = word_freq.get(clean_word, 0) + 1
unique_words.add(clean_word)
return…
How to Detect Hardcoded Secrets in Python Source Code
A Python utility that scans source code for common hardcoded secrets like API keys, passwords, tokens, and AWS credentials using regex patterns.
import re
def detect_secrets(text):
"""Detect potential hardcoded secrets in source code."""
patterns = {
'api_key': r'(?i)(api[_-]?key|apikey)\s*[=:]\s*["\']([^"\']+)["\']',
'password': r'(?i)(password|passwd)\s*[=:]\s*["\']([^"\']+)["\']',
'token': r'(?i)(\b(token|secret)\b)\s*[=:]\s…
Split a String into Multiple Lines by Width in Python
Demonstrates a word-wrap algorithm that splits a message into rows without exceeding a maximum width.
def split_message(text, max_width):
words = text.split()
rows = []
current_row = []
for word in words:
if len(" ".join(current_row + [word])) > max_width:
rows.append(" ".join(current_row))
current_row = [word]
else:
current_row.append(word)
if …
Dict Comprehension to Map Keys to Lengths in Python
Build a dictionary that maps each word to its character count using a dictionary comprehension.
words = ["apple", "banana", "cherry", "date", "elderberry"]
word_lengths = {word: len(word) for word in words}
print(word_lengths)
Set Comprehension for Unique Word Lengths in Python
Use a set comprehension to extract unique word lengths from a string, then sort and print the result.
text = "hello world hello python programming"
word_lengths = {len(word) for word in text.split()}
print("Unique word lengths:", word_lengths)
print("Sorted:", sorted(word_lengths))
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 Compute a Mock BLEU Score with n-gram Overlap in Python
Evaluate text similarity with a simplified BLEU score using word-level n-gram precision and a brevity penalty.
from collections import Counter
def bleu_score(reference, candidate, n=2):
"""
Compute a simplified BLEU score with n-gram precision and brevity penalty.
Mock demo using word-level n-grams.
"""
ref_tokens = reference.lower().split()
cand_tokens = candidate.lower().split()
# Compute n-…
How to Create a Mock LLM Judge Rubric Score in Python
Scores a response against a rubric by counting keyword matches, returning total, percentage, and per-criterion feedback.
def judge_score(response, rubric):
"""Mock LLM judge that scores a response against a rubric."""
total = 0
max_total = 0
feedback = []
for criterion, rubric_item in rubric.items():
max_points = rubric_item["max"]
description = rubric_item["description"]
# Simple mock scori…
How to Filter Blocked Words in Python
Scans input text against a moderation blocklist, returning blocked terms and their counts.
MODERATION_BLOCKLIST = {"spam", "scam", "fraud", "phishing", "malware", "abuse"}
def scan_text(text: str) -> dict:
normalized = text.lower()
words = normalized.replace(".", " ").replace(",", " ").replace("!", " ").replace("?", " ").split()
found_terms = []
for word in words:
if word in MO…
How to Filter Toxic Keywords in Python
Filter toxic keywords from text by replacing each occurrence with asterisks, useful as a basic guardrail for LLM inputs.
TOXIC_KEYWORDS = ["insult", "threat", "hate", "violence", "spam"]
def guardrails_filter(text: str, keywords: list[str] | None = None) -> str:
"""Filter out toxic keywords from the given text.
Args:
text: The input text to filter.
keywords: Optional keyword list. Defaults to TOXIC_KEYWORDS.
…
How to build a mock RAG pipeline in Python
Build a minimal Retrieval-Augmented Generation pipeline that retrieves the best-matching document by keyword overlap and generates a template-based answer.
def simple_rag_pipeline(question, documents):
"""
A minimal mock RAG pipeline: retrieve relevant context, then generate an answer.
"""
# Step 1: Retrieve — mock retrieval by simple keyword scoring
scores = []
for doc in documents:
doc_words = set(doc.lower().split())
question_wo…
Build a Command-Line Password Generator in Python
Generate cryptographically strong random passwords using Python's secrets module and print them for command-line use.
import secrets
import string
def generate_password(length=16):
"""Generate a cryptographically strong random password."""
alphabet = string.ascii_letters + string.digits + string.punctuation
password = ''.join(secrets.choice(alphabet) for _ in range(length))
return password
if __name__ == "__main__":…
Convert DOCX to Text by Unzipping XML in Python
Extract plain text from a .docx file by unzipping the container and parsing word/document.xml with regex, using only Python's standard library.
import zipfile
import re
from pathlib import Path
def docx_to_text_unzip_xml(docx_path: str) -> str:
"""Extract plain text from a .docx file by unzipping and parsing document.xml."""
docx_path = Path(docx_path)
if not docx_path.exists():
raise FileNotFoundError(f"File not found: {docx_path}")
…
Find Sensitive Information in Log Files with Python
Scan log files for emails, IP addresses, API keys, and passwords using regular expressions in Python.
import re
import os
from pathlib import Path
def find_sensitive_info(log_path):
"""Scans log files for patterns like emails, IPs, API keys, and passwords."""
patterns = {
'Email': r'[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}',
'IP Address': r'\b(?:\d{1,3}\.){3}\d{1,3}\b',
'API Key'…
Generate Strong Random Passwords with Custom Rules in Python
Build a configurable password generator using Python's secrets module that lets you toggle lowercase, uppercase, digits, and punctuation.
import secrets
import string
def generate_password(length=16, use_lower=True, use_upper=True, use_digits=True, use_punct=True):
pool = ''
if use_lower:
pool += string.ascii_lowercase
if use_upper:
pool += string.ascii_uppercase
if use_digits:
pool += string.digits
if use_pu…
How to Build an argparse CLI That Filters File Lines by Keyword in Python
This Python script is a command-line tool built with argparse that reads a text file and prints only the lines that contain (or don't contain) a given keyword.
import argparse
import sys
def main():
parser = argparse.ArgumentParser(description="Filter lines from a file by keyword.")
parser.add_argument("input", type=str, help="File to read")
parser.add_argument("keyword", type=str, help="Keyword to filter lines")
parser.add_argument("--contains", action="sto…
How to Create a Password Protected Zip Archive in Python
Generate a password-protected zip archive and verify password correctness using the standard library zipfile module.
import zipfile
import tempfile
import os
def create_password_protected_zip(zip_path, password: str, files: dict):
"""
Create a zip archive with password protection (mock encryption).
Args:
zip_path: Path where the zip file will be created
password: Password for the archive
files:…
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.