Reference library

Python Code Samples

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

150 matches
Strings & text easy

How to Check and Manipulate Strings in Python

Demonstrates core string inspection and transformation methods like case conversion, trimming, splitting, and membership checks on a sample string.

strings text-processing beginners
Python
text = "  Hello, Python Learners!  "

print(f"Original: '{text}'")
print(f"Lowercase: '{text.lower()}'")
print(f"Uppercase: '{text.upper()}'")
print(f"Title case: '{text.title()}'")
print(f"Stripped: '{text.strip()}'")
print(f"Length: {len(text)}")
print(f"Replace: '{text.replace('Python', 'Programming')}'")
print(f"S…
15 0 Open
Strings & text easy

How to Detect if a String Contains Only ASCII in Python

This code defines a function that checks whether every character in a given string is an ASCII character (Unicode code point < 128) and demonstrates it with multiple test cases.

ascii string validation
Python
def is_ascii_only(text: str) -> bool:
    """Return True if all characters in text are ASCII, False otherwise."""
    return all(ord(char) < 128 for char in text)


if __name__ == "__main__":
    # Test cases
    samples = [
        "Hello, world!",
        "Café au lait",
        "日本語テキスト",
        "ASCII only 123",
…
16 0 Open
Strings & text easy

How to Encode and Decode UTF-8 in Python

Convert a Python string to UTF-8 bytes with .encode() and back to text with .decode(), with a simple demo function.

utf-8 encode decode
Python
def encode_decode_demo(text: str):
    encoded = text.encode("utf-8")
    decoded = encoded.decode("utf-8")
    print(f"Original string: {text}")
    print(f"Encoded bytes: {encoded}")
    print(f"Decoded string: {decoded}")
    print(f"Match: {text == decoded}")

if __name__ == "__main__":
    encode_decode_demo("Hel…
13 0 Open
Strings & text easy

How to Escape HTML in Python

This code demonstrates how to use Python's `html.escape` function to safely encode user input for display in HTML, preventing XSS attacks.

html escaping security
Python
import html

def escape_user_input(user_input: str) -> str:
    """Escape HTML-sensitive characters for safe display."""
    return html.escape(user_input)

if __name__ == "__main__":
    sample_user_input = '<script>alert("XSS")</script> & \'quotes\''
    safe_output = escape_user_input(sample_user_input)
    print("…
13 0 Open
Strings & text easy

How to Format Text in Python (Beginner's Guide)

This beginner-friendly Python script demonstrates text formatting basics: stripping whitespace, converting to title case, replacing substrings, splitting into words, and generating a snippet.

string-manipulation text-formatting beginner
Python
text = "  hello world, welcome to python skillset!  "
cleaned = text.strip()
title_cased = cleaned.title()
replaced = title_cased.replace("Python", "PYTHON")
words = replaced.split()
word_count = len(words)
first_three = " ".join(words[:3])
snippet = first_three + "..."
print("Original:", repr(text))
print("Stripped:"…
13 0 Open
Strings & text easy

How to Strip Whitespace in Python

This code demonstrates how to remove leading and trailing whitespace from a string using the built-in strip() method.

string whitespace text-cleaning
Python
def strip_whitespace(text: str) -> str:
    return text.strip()

if __name__ == "__main__":
    sample = "   Hello, world!   "
    result = strip_whitespace(sample)
    print(f"Original: '{sample}'")
    print(f"Stripped: '{result}'")
13 0 Open
Strings & text easy

Python String isalpha() Method: Check if String is Alphabetic

This code defines a function that uses Python's str.isalpha() method to determine if a string contains only alphabetic characters, with a demonstration on several test strings.

string isalpha validation
Python
def is_alphabetic(s):
    return s.isalpha()

if __name__ == "__main__":
    test_strings = ["Hello", "Hello123", "World!", "Python", ""]
    for s in test_strings:
        print(f"{s!r}: {is_alphabetic(s)}")
12 0 Open
Strings & text easy

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.

text-processing string-methods word-count
Python
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…
13 0 Open
Lists & loops easy

How to Find the Maximum Value in a Python List

This code defines a function that finds the largest number in a list by iterating through it, returning None for an empty list, and demonstrates it on a sample list.

max list loop
Python
def find_max(numbers):
    if not numbers:
        return None
    max_value = numbers[0]
    for num in numbers[1:]:
        if num > max_value:
            max_value = num
    return max_value

if __name__ == "__main__":
    sample_list = [3, 7, 2, 9, 1, 9]
    result = find_max(sample_list)
    print(f"Maximum valu…
14 0 Open
Lists & loops easy

How to Sort a List in Python in Ascending and Descending Order

This code demonstrates three ways to sort a list in Python: returning a new sorted list with sorted(), reversing the sort order, and sorting a list in place with the list.sort() method.

sort sorted lists
Python
def get_sorted_data(numbers):
    """Return a new list sorted in ascending order."""
    return sorted(numbers)


def reverse_sort(data):
    """Return a new list sorted in descending order."""
    return sorted(data, reverse=True)


def sort_in_place(data):
    """Sort the given list in place (modifies original)."""
…
11 0 Open
Functions & basics easy

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.

default-parameters functions arguments
Python
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…
14 0 Open
Functions & basics easy

How to Define a Function with Default Parameter Values in Python

This code demonstrates defining a Python function with default parameter values, showing how to call it with zero, one, or two arguments.

functions default-parameters arguments
Python
def greet(name: str = "World", punctuation: str = "!") -> str:
    """Return a greeting message using default parameter values."""
    message = f"Hello, {name}{punctuation}"
    return message


if __name__ == "__main__":
    # Call with no arguments – uses both defaults
    print(greet())

    # Call with one argume…
12 0 Open
Functions & basics easy

How to Merge Lists in Python with Default Parameters

This Python function merges two lists using the + operator and demonstrates default parameters, allowing the second argument to be omitted.

functions default-parameters list
Python
def merge_lists(list1, list2=["default"]):
    """Merge two lists and return the combined result."""
    return list1 + list2


if __name__ == "__main__":
    # Example with default parameter
    print("With default:", merge_lists([1, 2, 3]))
    
    # Example with both arguments provided
    print("With custom:", me…
13 0 Open
Functions & basics easy

How to Return Multiple Values from a Python Function

This code demonstrates how a Python function can return multiple values as a tuple, and how to unpack that tuple into individual variables.

functions tuple return-values
Python
def get_user_stats(name, score, level):
    """Return multiple values as a tuple."""
    return name, score, level

if __name__ == "__main__":
    result = get_user_stats("Alice", 95, 3)
    print(result)
    print(type(result))
    
    # Unpacking into individual variables
    player_name, player_score, player_level…
15 0 Open
Functions & basics easy

How to Use Default Parameter Values in Python Functions

This code demonstrates how to define a Python function with default parameters and call it with varying numbers of arguments to see the defaults applied.

functions parameters defaults
Python
def greet(name, greeting="Hello", punctuation="!"):
    message = f"{greeting}, {name}{punctuation}"
    print(message)

if __name__ == "__main__":
    greet("Alice")
    greet("Bob", "Hi")
    greet("Charlie", "Hey", "?")
12 0 Open
Functions & basics easy

How to Use singledispatch for Type-Based Overloading in Python

This code demonstrates Python's functools.singledispatch decorator to create functions that behave differently based on the type of their first argument.

singledispatch overloading functools
Python
from functools import singledispatch

@singledispatch
def process(value):
    return f"Unknown type: {type(value).__name__}"

@process.register(int)
def _(value):
    return f"Integer: {value * 2}"

@process.register(str)
def _(value):
    return f"String: {value.upper()}"

@process.register(list)
def _(value):
    re…
11 0 Open
Functions & basics easy

Mutual Recursion for Even/Odd Check in Python

Implements even and odd checks using two functions that call each other recursively, demonstrating base cases and alternating calls.

recursion functions mutual-recursion
Python
def is_even(n):
    if n == 0:
        return True
    return is_odd(n - 1)

def is_odd(n):
    if n == 0:
        return False
    return is_even(n - 1)

if __name__ == "__main__":
    for num in range(0, 11):
        print(f"{num}: even={is_even(num)}, odd={is_odd(num)}")
11 0 Open
Errors & debugging easy

Handle ValueError and ZeroDivisionError in Python with try except

Learn how to catch ValueError and ZeroDivisionError in Python with a practical safe_divide function and demonstrate error handling for invalid conversions.

try-except valueerror zerodivisionerror
Python
def safe_divide(numerator, denominator):
    try:
        result = numerator / denominator
    except ValueError as e:
        print(f"ValueError caught: {e}")
        return None
    except ZeroDivisionError:
        print("Cannot divide by zero!")
        return None
    return result

# Test cases
print(safe_divide…
12 0 Open
Errors & debugging easy

How to Configure Python Logging with File Rotation

A complete demo that sets up a logger with a rotating file handler, writes several log entries, and shows the contents of the current log file.

logging file-handler rotating-file-handler
Python
import logging
from logging.handlers import RotatingFileHandler

logger = logging.getLogger("rotating_logger")
logger.setLevel(logging.DEBUG)

file_handler = RotatingFileHandler(
    "app.log",
    maxBytes=100,
    backupCount=3
)
file_handler.setFormatter(
    logging.Formatter("%(asctime)s - %(levelname)s - %(messa…
12 0 Open
Errors & debugging easy

How to Handle ValueError and Multiple Exceptions in Python

This code demonstrates try/except blocks for beginners, handling ZeroDivisionError, TypeError, and ValueError with two practical functions: dividing numbers and parsing strings to floats.

try-except valueerror exception-handling
Python
def divide_numbers(a, b):
    """Divide two numbers with error handling for beginners."""
    try:
        result = a / b
        print(f"{a} / {b} = {result}")
        return result
    except ZeroDivisionError:
        print(f"Error: Cannot divide {a} by zero!")
    except TypeError:
        print(f"Error: Both argu…
13 0 Open
Errors & debugging easy

How to Use try except else finally in Python

Demonstrates the correct order of try/except/else/finally blocks in Python with a safe division function.

try-except error-handling flow-control
Python
def safe_divide(numerator, denominator):
    try:
        result = numerator / denominator
    except ZeroDivisionError:
        print("Error: Cannot divide by zero!")
    except TypeError:
        print("Error: Both arguments must be numbers!")
    else:
        print(f"Division successful: {numerator} / {denominator…
13 0 Open
Errors & debugging medium

Implement circuit breaker open after failures demo in Python

A minimal CircuitBreaker class that calls a function and automatically 'opens' after a set number of consecutive failures, blocking further calls with a RuntimeError.

circuit-breaker resilience error-handling
Python
import time
from datetime import datetime


class CircuitBreaker:
    def __init__(self, threshold=3):
        self.threshold = threshold
        self.failure_count = 0
        self.is_open = False

    def call(self, func, *args, **kwargs):
        if self.is_open:
            raise RuntimeError("Circuit is OPEN")
  …
12 0 Open
Errors & debugging easy

Split try except ValueError handler for beginners in Python

Demonstrates how to handle ValueError and ZeroDivisionError separately using try/except blocks, with beginner-friendly examples for parsing and division.

try-except valueerror zerodivisionerror
Python
def parse_number(text):
    try:
        number = int(text)
        return f"Parsed successfully: {number}"
    except ValueError as error:
        return f"Conversion failed: {error}"

def divide_numbers(dividend, divisor):
    try:
        result = dividend / divisor
        return f"Division result: {result}"
    e…
13 0 Open
Files & data easy

How to Find HTML Elements by Tag, Class, ID, CSS Selector, and Attribute in BeautifulSoup

Parse an HTML string with BeautifulSoup and demonstrate five distinct ways to locate elements: by tag name, by class, by ID, by CSS selector, and by attribute.

beautifulsoup html parsing
Python
from bs4 import BeautifulSoup

html_content = """
<html><body>
    <h1 id="title" class="heading">Hello World</h1>
    <p class="content">First paragraph</p>
    <p class="content special">Second paragraph</p>
    <a href="https://example.com" class="link">Click here</a>
    <div id="footer">
        <p>© 2024</p>
   …
62 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.