Reference library

Python Code Samples

Copy-ready Python snippets by topic and difficulty — short, focused, and runnable in the browser editor.

315 matches
Strings & text easy

Build CSV row from Python list with proper quoting

Converts a list of fields into a properly quoted CSV row string using the csv module.

csv quotes strings
Python
import csv
import io


def build_csv_row(fields):
    output = io.StringIO()
    writer = csv.writer(output)
    writer.writerow(fields)
    return output.getvalue().rstrip("\r\n")


if __name__ == "__main__":
    fields = ["Alice", "Smith", "123 Main St, Apt 4B", "alice@example.com"]
    print(build_csv_row(fields))
15 0 Open
Strings & text easy

Build a Secure Password Strength Checker in Python

A Python function that evaluates password strength based on length and character diversity, returning Weak, Moderate, or Strong.

password security regex
Python
import re

def password_strength(password: str) -> str:
    score = 0
    if len(password) >= 8:
        score += 1
    if re.search(r'[a-z]', password):
        score += 1
    if re.search(r'[A-Z]', password):
        score += 1
    if re.search(r'\d', password):
        score += 1
    if re.search(r'[!@#$%^&*(),.?":…
54 0 Open
Strings & text easy

How to Build a Basic Text Processor in Python

Split text into sentences, count words, find the longest word, and convert text to uppercase — all with pure Python string methods.

string text-processing split
Python
text = """The quick brown fox jumps over the lazy dog.
Python is a powerful programming language.
Keep practicing every single day!"""

sentences = text.split(". ")
word_count = 0
longest_word = ""

for sentence in sentences:
    words = sentence.split()
    word_count += len(words)
    for word in words:
        clea…
14 0 Open
Strings & text easy

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.

text-processing strings word-count
Python
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…
14 0 Open
Strings & text easy

How to Transform Text in Python with a Helper Function

Build a simple Python helper to strip extra whitespace and convert text to upper, lower, or title case.

strings text helper
Python
def transform_text(text, upper=False, lower=False, strip_whitespace=False, title_case=False):
    """Apply common string transformations for beginners."""
    result = text

    if strip_whitespace:
        result = " ".join(result.split())

    if upper and lower:
        raise ValueError("Cannot apply both upper and…
12 0 Open
Strings & text easy

How to Translate Characters in a String with str.maketrans in Python

Build and apply character translation tables with str.maketrans and str.translate to replace, delete, or remap letters in a Python string.

string translation character-mapping
Python
def translate_demo():
    # Build a translation table: a→1, e→2, i→3, o→4, u→5
    table = str.maketrans("aeiou", "12345")
    
    text = "Hello, Python world! Keep coding, friend."
    translated = text.translate(table)
    
    print(f"Original: {text}")
    print(f"Translated: {translated}")
    
    # Example wit…
11 0 Open
Strings & text easy

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.

string-manipulation text-processing word-count
Python
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."""
 …
12 0 Open
Lists & loops easy

How to Build a Frequency Map from a List in Python

This code builds a dictionary that maps each unique element in a list to its count using the Counter class from the collections module.

counter frequency dictionary
Python
from collections import Counter

def build_frequency_map(values):
    """Return a dictionary mapping each unique value to its frequency."""
    return dict(Counter(values))

if __name__ == "__main__":
    data = ["apple", "banana", "apple", "cherry", "banana", "apple"]
    freq_map = build_frequency_map(data)
    prin…
13 0 Open
Lists & loops easy

How to Build a Running Maximum List in Python

Compute a list where each element is the maximum of all numbers seen so far from an input list.

running-max iteration lists
Python
def running_maximum(numbers):
    result = []
    current_max = float('-inf')
    for num in numbers:
        if num > current_max:
            current_max = num
        result.append(current_max)
    return result

if __name__ == "__main__":
    numbers = [3, 1, 4, 1, 5, 9, 2, 6]
    max_list = running_maximum(number…
15 0 Open
Lists & loops easy

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.

text-processing loops lists
Python
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…
12 0 Open
Lists & loops easy

How to Calculate a Cumulative Sum in Python

Build a new list where each element equals the running total of all numbers up to that index in the original list.

lists cumulative-sum loops
Python
numbers = [1, 2, 3, 4, 5]
cumulative_sum = []
running_total = 0

for num in numbers:
    running_total += num
    cumulative_sum.append(running_total)

print(cumulative_sum)
12 0 Open
Functions & basics easy

Benchmark list append vs comprehension in Python

This micro-benchmark compares the speed of building a list with a for loop and append versus a list comprehension, using the timeit module to get precise timings.

timeit benchmark performance
Python
import timeit

# Build a list of the first 1,000,000 integers using append in a loop
def append_loop(n=1_000_000):
    result = []
    for i in range(n):
        result.append(i)
    return result

# Build the same list using a list comprehension
def comprehension(n=1_000_000):
    return [i for i in range(n)]

if __n…
13 0 Open
Functions & basics easy

Build a Context Manager in Python with contextlib.contextmanager

Create a reusable context manager that safely opens and closes files using the contextlib contextmanager decorator.

context manager contextlib file handling
Python
from contextlib import contextmanager

@contextmanager
def managed_file(filename, mode='r'):
    """Context manager that opens and closes a file safely."""
    file = open(filename, mode)
    yield file
    file.close()

if __name__ == "__main__":
    # Write a sample file
    with managed_file("sample.txt", "w") as f…
14 0 Open
Functions & basics easy

Build a Progress Callback Function for Loops in Python

Create a reusable progress callback that receives per-step data and lets callers log or update a UI as a loop runs.

callback loops progress
Python
def run_with_progress(items, desc="Processing", step_callback=None):
    """Run a loop with progress updates via callback."""
    total = len(items)
    for idx, item in enumerate(items):
        # Process the item (simulated work here)
        result = item * 2

        # Build progress data dictionary
        if ste…
14 0 Open
Functions & basics easy

Format CLI help text in Python

Build a readable usage string for a command-line tool, aligning flags and wrapping descriptions with the textwrap module.

cli textwrap formatting
Python
import textwrap


def format_help(command_name: str, description: str, options: list[tuple[str, str]]) -> str:
    """Format CLI help text into a readable usage string."""
    header = f"Usage: {command_name} [OPTIONS]"
    lines = [header, "", description, "", "Options:"]

    for flag, help_text in options:
        …
12 0 Open
Functions & basics easy

How to Add a Dry Run Flag to a Python CLI Command

Build a Python CLI command with a --dry-run flag that previews actions and exits before making real changes.

argparse cli dry-run
Python
import argparse
import sys

def main():
    parser = argparse.ArgumentParser(description="Sample CLI command with dry-run flag")
    parser.add_argument("--name", required=True, help="Name to greet")
    parser.add_argument("--dry-run", action="store_true", dest="dry_run",
                        help="Show what would…
11 0 Open
Functions & basics easy

How to Build Partial Functions with functools.partial in Python

Create reusable partial functions that pre-fill arguments using functools.partial, like making square and cube functions from a general power function.

functools partial higher-order-functions
Python
```python
from functools import partial

def power(base, exponent):
    """Calculate base raised to the exponent power."""
    return base ** exponent

# Create partial functions for common powers
square = partial(power, exponent=2)
cube = partial(power, exponent=3)

if __name__ == "__main__":
    squares = [square(x)…
12 0 Open
Functions & basics easy

How to Build a Simple Decorator That Logs Function Calls in Python

This code shows how to create a reusable decorator that logs each function call, including arguments, return value, and execution time.

decorator logging functools
Python
import functools
import time

def log_calls(func):
    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        print(f"Calling {func.__name__} with args={args}, kwargs={kwargs}")
        start = time.time()
        result = func(*args, **kwargs)
        end = time.time()
        print(f"{func.__name__} return…
11 0 Open
Functions & basics medium

How to Build a Subcommand Parser Tree with argparse in Python

Create a CLI with nested subcommands (like git) using argparse subparsers, where each subcommand maps to its own handler function.

argparse cli subparsers
Python
import argparse


def cmd_add(args):
    print(f"Adding {args.num1} + {args.num2} = {args.num1 + args.num2}")


def cmd_sub(args):
    print(f"Subtracting {args.num1} - {args.num2} = {args.num1 - args.num2}")


def main():
    parser = argparse.ArgumentParser(prog="calculator")
    subparsers = parser.add_subparsers(d…
12 0 Open
Functions & basics medium

How to Create a Counter Closure in Python

Build a closure in Python that remembers and increments a counter across calls without using global variables.

closures nonlocal state
Python
def create_counter(start=0):
    count = start
    def increment():
        nonlocal count
        count += 1
        return count
    return increment

if __name__ == "__main__":
    counter = create_counter(10)
    print(counter())
    print(counter())
    print(counter())
12 0 Open
Functions & basics easy

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.

argparse cli command line
Python
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',
         …
11 0 Open
Functions & basics easy

How to Use Default Parameters in Python Functions

Create a simple function with default parameters to build flexible, reusable greetings in Python.

functions default-parameters basics
Python
def greet(name, greeting="Hello", punctuation="!"):
    """Return a personalized greeting message."""
    return f"{greeting}, {name}{punctuation}"


if __name__ == "__main__":
    print(greet("Alice"))               
    print(greet("Bob", "Hi"))           
    print(greet("Charlie", greeting="Hey", punctuation="?"))…
14 0 Open
Errors & debugging easy

How to Build a Simple Debug Timer in Python

Create a context manager class to time the execution of a code block with a one-line printout.

debugging context-manager performance
Python
import time


class DebugTimer:
    """Context manager that times the execution of a code block."""

    def __init__(self, label="Operation"):
        self.label = label
        self.start_time = None

    def __enter__(self):
        self.start_time = time.perf_counter()
        return self

    def __exit__(self, e…
15 0 Open
Errors & debugging easy

How to Build an Error Code Enum in Python

Define an API error code enum with descriptions and build structured error payloads for HTTP responses.

enum error-handling api
Python
from enum import Enum

class APIErrorCode(Enum):
    SUCCESS = 0
    BAD_REQUEST = 400
    UNAUTHORIZED = 401
    FORBIDDEN = 403
    NOT_FOUND = 404
    CONFLICT = 409
    INTERNAL_ERROR = 500


def describe_error(code):
    descriptions = {
        APIErrorCode.SUCCESS: "Request completed successfully",
        APIE…
11 0 Open

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

  1. Pick a topic section — strings, lists, files, functions, and more
  2. Open a sample, read How it works, and copy the code block
  3. 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.