Python Code
Samples
Copy-ready Python snippets by topic and difficulty — short, focused, and runnable in the browser editor.
How to build a text helper in Python for beginners
This code provides easy-to-use functions for cleaning text, removing punctuation, counting word frequencies, and summarizing strings — perfect for beginners.
def clean_text(text: str) -> str:
"""Clean and normalize a text string."""
text = text.strip()
text = text.replace(" ", " ")
text = text.capitalize()
text = text.replace(".", ".")
return text
def remove_punctuation(text: str) -> str:
"""Remove common punctuation marks from a string."""
…
How to wrap long text to a specified width in Python
Uses Python's textwrap.fill to wrap a long string to a specified width at word boundaries, preserving readability in console output or logs.
import textwrap
text = """This is a long piece of text that definitely exceeds the width limit
if we try to print it on a single line without any wrapping applied."""
wrapped = textwrap.fill(text, width=40)
print(wrapped)
Python String Helper Functions for Beginners
A set of beginner-friendly Python functions that count words, reverse text, convert to title case, strip punctuation, and compute character frequency from a string.
def count_words(text):
"""Count the number of words in a string."""
return len(text.split())
def reverse_text(text):
"""Reverse the entire string."""
return text[::-1]
def title_case(text):
"""Capitalize the first letter of each word."""
return text.title()
def remove_punctuation(text):
…
Reverse Words in a Sentence While Keeping Punctuation in Python
Reverses the order of words in a sentence while leaving punctuation and spaces in their original positions using Python's re module.
def reverse_words_preserving_punctuation(sentence: str) -> str:
import re
# Split into words and punctuation tokens
tokens = re.findall(r'\w+|[^\w\s]|\s+', sentence)
words = [t for t in tokens if re.fullmatch(r'\w+', t)]
words.reverse()
result_parts = []
word_index = 0
for token in toke…
String helpers in Python: stats, reverse, and remove vowels
Three beginner-friendly Python functions compute text statistics, reverse word order, and strip vowels from a string.
def text_stats(text: str) -> dict:
"""Return basic statistics for a given text string."""
words = text.split()
return {
"characters": len(text),
"words": len(words),
"sentences": text.count(".") + text.count("!") + text.count("?"),
"uppercase": sum(1 for c in text if c.isupp…
Text Processor Functions for Beginners in Python
Demonstrates simple text-processing utilities: word counting, word reversal, whitespace normalization, and lowercase conversion using basic string methods.
def count_words(text):
"""Return the number of words in a string."""
return len(text.split())
def reverse_words(text):
"""Return the text with words in reverse order."""
return ' '.join(text.split()[::-1])
def remove_extra_spaces(text):
"""Return text with extra whitespace collapsed to a single s…
How to Build a Text Processor with Lists and Loops in Python
A beginner-friendly Python script that analyzes text by counting sentences, words, and word lengths using lists and for loops, then prints the results.
def process_text(text):
"""Simple text processor for beginners using lists and loops."""
sentences = text.replace('!', '.').replace('?', '.').split('.')
words = text.split()
word_counts = []
for sentence in sentences:
sentence_word_count = len(sentence.split())
word_counts.appe…
How to Process Text into Words in Python
Splits a string into words, strips punctuation, and returns a list of uppercase words using a loop.
def convert_text_processor(text):
words = text.split()
processed = []
for word in words:
clean = word.strip('.,!?;:')
if len(clean) > 0:
processed.append(clean.upper())
return processed
if __name__ == "__main__":
sample_text = "Hello, world! This is a Python e…
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…
How to Validate Text Against Forbidden Words in Python
Checks whether a given text contains any forbidden words and returns a tuple with validity and offending words.
def validate_text(text, forbidden_words):
"""
Checks that text does not contain any forbidden words.
Returns (is_valid, offending_words) tuple.
"""
words = text.lower().split()
found = [word for word in words if word in forbidden_words]
return len(found) == 0, found
if __name__ == "__main…
How to Create Functions with Default Parameters in Python
This code defines two Python functions using default parameters to handle missing arguments gracefully, demonstrating how to work with optional inputs and keyword arguments.
def greet(name="Guest", greeting="Hello", punctuation="!"):
"""Generate a greeting message using default parameters."""
return f"{greeting}, {name}{punctuation}"
def create_profile(username="anonymous", age=0, city="Unknown", active=True):
"""Create a user profile dictionary with default values."""
r…
How to Use *args and **kwargs in Python Functions
Implement a variadic function that accepts arbitrary positional and keyword arguments using *args and **kwargs.
def display_info(title, *args, **kwargs):
"""Display positional and keyword arguments received."""
print(f"Title: {title}")
print(f"Additional positional args ({len(args)}):")
for i, arg in enumerate(args, 1):
print(f" {i}. {arg}")
print(f"Keyword args ({len(kwargs)}):")
for key, value…
How to Use Default Parameter Values in Python Functions
Shows how to define and call Python functions with default parameter values, including overriding some or all defaults and using keyword arguments.
def greet(name, greeting="Hello", punctuation="!"):
"""Return a greeting message using default parameters."""
return f"{greeting}, {name}{punctuation}"
if __name__ == "__main__":
# Using defaults
print(greet("Alice"))
# Overriding first default
print(greet("Bob", "Hi"))
# Overrid…
How to Use Default Parameters in Python Functions
Define a Python function with default parameters and call it using positional and keyword arguments.
def greet(name, greeting="Hello", punctuation="!"):
"""Concatenate a greeting message with default parameters."""
return f"{greeting}, {name}{punctuation}"
if __name__ == "__main__":
print(greet("Alice")) # Uses both defaults
print(greet("Bob", "Hi")) # Uses default punctua…
How to Use Keyword-Only Arguments in Python Functions
Define Python functions with keyword-only arguments using the * separator to enforce clarity and prevent positional misuse.
def greet(name, *, greeting="Hello", punctuation="!"):
"""Greet someone with a customizable message using keyword-only arguments."""
message = f"{greeting}, {name}{punctuation}"
return message
if __name__ == "__main__":
# Basic call with only the positional argument
print(greet("Alice"))
# Al…
How to Wrap a Low Level Error in a Higher Level Exception in Python
Wrap low-level exceptions in a higher-level exception while preserving the original cause with the `from` keyword.
class LowLevelError(Exception):
pass
class HighLevelError(Exception):
pass
def low_level_operation():
raise LowLevelError("storage drive failed to respond")
def high_level_operation():
try:
low_level_operation()
except LowLevelError as e:
raise HighLevelError(f"database operation…
Redact secrets from log message formatter in Python
Build a custom logging.Formatter that masks passwords, API keys, and credit card numbers in log output.
import re
import logging
class RedactingFormatter(logging.Formatter):
"""Formatter that masks sensitive data in log messages."""
SENSITIVE_PATTERNS = [
(re.compile(r'password[=:]\s*\S+', re.IGNORECASE), 'password=[REDACTED]'),
(re.compile(r'api[_-]?key[=:]\s*\S+', re.IGNORECASE), 'api_key…
Build a Secure Local Password Vault with Encrypted Storage in Python
A Python class that stores and retrieves passwords in an encrypted JSON file using Fernet symmetric encryption from the cryptography library.
import json
import os
import base64
import hashlib
from cryptography.fernet import Fernet
from getpass import getpass
class PasswordVault:
def __init__(self, vault_file="vault.json", key_file="vault.key"):
self.vault_file = vault_file
self.key_file = key_file
self.key = self._load_or_creat…
Extract Hyperlinks from Word Documents in Python
Parses a .docx file using Python's standard library to extract every hyperlink's display text and target URL.
import zipfile
from pathlib import Path
import xml.etree.ElementTree as ET
def extract_hyperlinks_from_docx(filepath: str) -> list[dict]:
"""
Extract all hyperlinks from a .docx file.
Returns a list of dicts with 'text' and 'target' keys.
"""
hyperlinks = []
with zipfile.ZipFile(Path(filepath)…
Count Word Frequency in Python with dict
Count how often each word appears in a text using Python's collections.Counter and regular expressions.
from collections import Counter
import re
def count_word_frequency(text):
"""Count frequency of each word in text (case-insensitive)."""
words = re.findall(r"\b\w+\b", text.lower())
return dict(Counter(words))
if __name__ == "__main__":
sample_text = "The quick brown fox jumps over the lazy dog. The …
Count Words in Python with Dictionaries and Sets
Text analysis example that counts total words, finds unique words with a set, and tallies character frequencies with a dictionary.
def analyze_text(text: str) -> dict:
"""Count words, find unique words, and show common characters."""
words = text.lower().split()
word_count = len(words)
unique_words = set(words)
char_counts = {}
for word in words:
for char in word:
if char.isalpha():
…
Count word frequency in Python with dict and Counter
Count how often each word appears in a string using Counter, converted to a plain dict, and print results alphabetically.
from collections import Counter
import re
def count_word_frequency(text):
words = re.findall(r'\b\w+\b', text.lower())
return dict(Counter(words))
if __name__ == "__main__":
sample_text = "The quick brown fox jumps over the lazy dog. The dog barks, and the fox runs."
frequency = count_word_frequency(…
How to Count Word Frequencies in Python
Count how often each word appears in a string and list the unique words using Python dictionaries and sets.
def text_processor(text):
words = text.lower().split()
word_count = {}
for word in words:
word_count[word] = word_count.get(word, 0) + 1
unique_words = set(words)
return word_count, unique_words
if __name__ == "__main__":
sample_text = "The quick brown fox jumps over the lazy dog and t…
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.