Python Code
Samples
Easy snippets you can copy, study, and run in the browser editor.
How to Filter a List of Strings by Keyword in Python
A helper function filters a list of strings by a keyword search with optional case sensitivity.
def filter_strings(items, keyword, case_sensitive=False):
"""
Filter a list of strings by a keyword.
Args:
items: list of strings to filter
keyword: substring to search for
case_sensitive: if True, match case exactly
Returns:
list of strings containing the keyw…
How to Sort Text in Python with a Simple Helper Function
A compact helper function that sorts a list of strings or splits a string into words and sorts them alphabetically, with optional reverse ordering.
def sort_text(data, reverse=False):
"""
Sort a list of strings (or a single string split into words) alphabetically.
"""
if isinstance(data, str):
words = data.split()
else:
words = [str(item) for item in data]
return sorted(words, reverse=reverse)
if __name__ == "__main__":
…
Repeat a string n times with a separator in Python
Repeats a string a given number of times, joining the repetitions with an optional separator, with a guard for non-positive counts.
def repeat_string_with_separator(s, n, sep=''):
"""
Repeats a string n times, joining with a separator.
Args:
s (str): The string to repeat.
n (int): Number of repetitions.
sep (str): Separator between repetitions (default: '').
Returns:
str: The repeated strin…
How to Sort a List of Dictionaries by a Key in Python
Sort a list of dictionaries by a specified key field, optionally in descending order, using Python's built-in sorted() function.
def sort_dicts_by_key(data, key, reverse=False):
return sorted(data, key=lambda item: item.get(key), reverse=reverse)
if __name__ == "__main__":
people = [
{"name": "Alice", "age": 30},
{"name": "Bob", "age": 25},
{"name": "Charlie", "age": 35},
]
sorted_by_age = sort_dicts_b…
How to Validate List Data in Python
A beginner-friendly validation helper that checks if data is a list, enforces minimum length, and optionally verifies item types with clear error messages.
def validate_data(data, expected_types=None, min_length=1):
"""Validate that data is a non-empty list and optionally check item types."""
if not isinstance(data, list):
return False, f"Expected a list, got {type(data).__name__}"
if len(data) < min_length:
return False, f"List must have…
Call a Function Dynamically by Name in Python
Use globals() to look up and call a function by its name as a string, with optional arguments.
def greet():
return "Hello from greet!"
def add(a, b):
return a + b
def multiply(a, b):
return a * b
if __name__ == "__main__":
func_name = "add"
args = (3, 5)
# Call function dynamically by name from globals
result = globals()[func_name](*args)
print(f"{func_name}({', '.join(ma…
Create a retry decorator with max attempts in Python
A decorator that retries a function up to a specified number of times when it raises an exception, with an optional delay between attempts.
import functools
import time
def retry(max_attempts, delay=0.1):
"""Retry a function up to max_attempts times on exception."""
def decorator(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
for attempt in range(1, max_attempts + 1):
try:
…
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 Parse Command Line Arguments in Python with argparse
Build a CLI that accepts positional integers, an optional --sum flag, and a --verbose switch, all with Python's standard argparse library.
import argparse
def main():
parser = argparse.ArgumentParser(description='Process some integers.')
parser.add_argument('numbers', metavar='N', type=int, nargs='+',
help='an integer for the accumulator')
parser.add_argument('--sum', dest='accumulate', action='store_const',
…
How to Parse Function Parameters with Defaults in Python
Create Python functions with default parameter values to make arguments optional and provide sensible fallbacks.
def greet(name, greeting="Hello", punctuation="!"):
"""Greet a person with customizable greeting and punctuation."""
return f"{greeting}, {name}{punctuation}"
def describe_fruit(fruit, color="unknown", ripe=False):
"""Describe a fruit with optional attributes."""
status = "ripe" if ripe else "not ripe…
How to Use Optional Return in Python Instead of Raising Exceptions
A Python function returns None for missing dictionary keys instead of raising KeyError, enabling graceful lookup handling with type hints.
from typing import Optional
def find_user(users: dict, user_id: int) -> Optional[dict]:
"""
Look up a user by ID. Returns the user dict if found,
otherwise returns None instead of raising KeyError.
"""
return users.get(user_id)
def main() -> None:
users = {
1: {"name": "Alice", "ema…
Implement a Context Manager That Suppresses Exceptions in Python
Shows how to write a custom context manager that catches specified exceptions and optionally re-raises others, plus the stdlib contextlib.suppress alternative.
import contextlib
class SuppressExceptions:
def __init__(self, *exceptions):
self.exceptions = exceptions
def __enter__(self):
return self
def __exit__(self, exc_type, exc_val, exc_tb):
if exc_type is None:
return False
if not self.exceptions or exc_type in se…
How to Parse JSON from LLM Model Output Fence in Python
Extract and parse a JSON object from a language model's output that may be wrapped in triple-backtick fences with an optional language tag.
import json
import re
def parse_json_from_fence(text):
"""
Extract JSON object from a model output that may be wrapped in
triple-backtick fences with optional language tag.
"""
# Match content inside
How to Build a CLI with argparse in Python
Create a beginner-friendly command-line tool in Python that processes multiple filenames with optional flags for verbose output and uppercase conversion.
import argparse
def main():
parser = argparse.ArgumentParser(
description="A simple CLI to process files with optional verbose mode."
)
parser.add_argument("filenames", nargs="+", help="Files to process")
parser.add_argument("-v", "--verbose", action="store_true", help="Print extra details")
…
How to Build a Python argparse CLI for Beginners
Build a beginner-friendly command-line interface using Python's argparse module with positional and optional arguments.
import argparse
def greet(name, greeting="Hello", uppercase=False):
message = f"{greeting}, {name}!"
if uppercase:
message = message.upper()
return message
def main():
parser = argparse.ArgumentParser(description="A simple CLI greet tool for beginners.")
parser.add_argument("name", help="…
How to Build a Simple Python CLI with argparse
Create a friendly command-line greeting tool with argparse that accepts a positional name and optional flags for custom greetings and uppercase output.
import argparse
def greet(name, greeting="Hello", uppercase=False):
message = f"{greeting}, {name}!"
return message.upper() if uppercase else message
if __name__ == "__main__":
parser = argparse.ArgumentParser(
description="A simple greeting tool to demonstrate argparse basics."
)
parser.…
How to Build a Simple argparse CLI in Python
Create a beginner-friendly command-line tool with argparse that reads a file, optionally uppercases its lines, and prints a configurable number of lines.
import argparse
def main():
parser = argparse.ArgumentParser(
description="Automate file processing with a simple CLI tool."
)
parser.add_argument("filename", help="Path to the input file")
parser.add_argument("--uppercase", action="store_true", help="Convert text to uppercase")
parser.add…
How to Build a Simple argparse CLI in Python
Build a beginner-friendly command-line tool with argparse that greets a user, with optional greeting text and uppercase output.
import argparse
def greet(name, greeting="Hello", uppercase=False):
message = f"{greeting}, {name}!"
if uppercase:
message = message.upper()
return message
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="Simple CLI greeting tool")
parser.add_argument("name", help=…
How to Build an argparse Command-Line Tool in Python
Create a simple file-info CLI with argparse that counts lines and prints file size, with optional verbose and output flags.
import argparse
import os
from pathlib import Path
def process_file(filepath, verbose=False):
"""Read a file and report its size and line count."""
path = Path(filepath)
if not path.exists():
raise FileNotFoundError(f"File not found: {filepath}")
content = path.read_text()
lines = conten…
How to Create a Simple Python CLI with argparse
Build a beginner-friendly command-line tool with argparse that accepts positional and optional arguments to greet users flexibly.
import argparse
def greet(name, greeting="Hello", uppercase=False):
message = f"{greeting}, {name}!"
return message.upper() if uppercase else message
def main():
parser = argparse.ArgumentParser(
description="A simple CLI tool that greets users."
)
parser.add_argument(
"name",
…
How to Implement argparse CLI Command in Python
Build a beginner-friendly command-line tool with argparse that accepts positional and optional arguments, flags, and prints a customizable greeting.
import argparse
def main():
parser = argparse.ArgumentParser(description="A simple CLI tool to greet users.")
parser.add_argument("name", help="Your name")
parser.add_argument("-g", "--greeting", default="Hello", help="Greeting word (default: Hello)")
parser.add_argument("--uppercase", action="store_…
How to Parse CLI Arguments in Python with argparse
Build a beginner-friendly CLI with argparse that accepts optional --name, --greeting, and --uppercase flags, then prints a customizable greeting.
import argparse
def main():
parser = argparse.ArgumentParser(description="Greet a user with optional customization.")
parser.add_argument("--name", default="world", help="Name to greet")
parser.add_argument("--greeting", default="Hello", help="Greeting word")
parser.add_argument("--uppercase", action=…
How to Sort Command-Line Arguments in Python
Build a beginner-friendly argparse CLI that sorts numbers or words passed as arguments, with an optional reverse flag.
import argparse
def main():
parser = argparse.ArgumentParser(description="Sort numbers or words from the command line.")
parser.add_argument("items", nargs="+", help="Items to sort (numbers or words)")
parser.add_argument("--reverse", "-r", action="store_true", help="Sort in descending order")
args =…
How to validate argparse CLI commands in Python
Build a beginner-friendly command-line argument parser with argparse, including required and optional arguments, plus simple validation for age.
import argparse
def main():
parser = argparse.ArgumentParser(description="Validate CLI arguments for beginners.")
parser.add_argument("name", type=str, help="Your name.")
parser.add_argument("--age", type=int, default=None, help="Your age (optional).")
parser.add_argument("--verbose", action="store_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.