Reference library

Python Code Samples

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

136 matches
Strings & text easy

Automatically Detect Weak Passwords from Large Password Lists in Python

This Python script identifies weak passwords from a list by checking length, common patterns, sequential characters, and uniform characters, returning those that fail the security checks.

password security validation
Python
import re

COMMON_PASSWORDS_FILE = "common_passwords.txt"

def is_weak(password):
    # Check length
    if len(password) < 8:
        return True
    # Check for common patterns
    if password.lower() in {"password", "123456", "qwerty", "letmein", "admin", "welcome"}:
        return True
    # Check for sequential c…
54 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'[!@#$%^&*(),.?":…
55 0 Open
Strings & text easy

How to Check Palindrome in Python (Ignore Case and Spaces)

Check whether a string is a palindrome while ignoring case, spaces, and all non-alphanumeric characters using Python's filter and string reversal.

palindrome string case-insensitive
Python
def is_palindrome(text: str) -> bool:
    cleaned = ''.join(char.lower() for char in text if char.isalnum())
    return cleaned == cleaned[::-1]

if __name__ == "__main__":
    test_cases = [
        "A man, a plan, a canal: Panama",
        "race a car",
        "Was it a car or a cat I saw?",
        "hello",
      …
14 0 Open
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 Check if a String Ends with a File Extension in Python

This code checks whether a filename ends with any of a list of file extensions, handling case insensitivity.

file-extension string-methods endswith
Python
def ends_with_extension(filename, extensions):
    """Check if a filename ends with any of the given extensions."""
    lower_name = filename.lower()
    return any(lower_name.endswith(ext.lower()) for ext in extensions)

if __name__ == "__main__":
    # Test cases
    test_files = ["report.pdf", "image.PNG", "script.…
17 0 Open
Strings & text easy

How to Check if a String Starts With a Prefix Case-Insensitively in Python

This code defines a function that checks if a string starts with a given prefix, ignoring case, using the lower() method.

string-methods case-insensitive startswith
Python
def starts_with_case_insensitive(text, prefix):
    """Check if a string starts with a given prefix, ignoring case."""
    return text.lower().startswith(prefix.lower())


if __name__ == "__main__":
    test_strings = [
        ("Hello World", "hello"),
        ("Python Programming", "PYTHON"),
        ("Data Science"…
15 0 Open
Strings & text easy

How to Check if a String is Alphanumeric in Python

Uses the built-in str.isalnum() method to test whether a string contains only letters and numbers.

string alphanumeric validation
Python
def is_alphanumeric(s: str) -> bool:
    return s.isalnum()

if __name__ == "__main__":
    test_cases = ["Hello123", "Hello World", "12345", "", "Hello@World", "Python3"]
    for case in test_cases:
        result = is_alphanumeric(case)
        print(f"{case!r:15} -> {result}")
13 0 Open
Strings & text easy

How to Check if a String is Numeric in Python

This code provides a function to determine if a string represents a valid numeric value using Python's built-in float() conversion.

numeric validation strings
Python
def is_numeric(s):
    """Check if a string represents a valid numeric value."""
    try:
        float(s)
        return True
    except (ValueError, TypeError):
        return False

if __name__ == "__main__":
    test_cases = ["123", "-45.67", "3.14e10", "0x1A", "abc", "12.5.6", "  42  ", ""]
    for case in test_c…
13 0 Open
Strings & text easy

How to Detect Expired Domains Using Python

Parse a list of domain registration data and compare expiry dates to today to find expired domains.

datetime date-parsing domain-check
Python
import datetime

# List of test domains with fake registration and expiry dates
# Format: (domain, registration_date, expiry_date)
test_domains = [
    ('example.com', '2020-01-15', '2024-01-15'),  # Expired
    ('google.com', '1997-09-15', '2026-09-15'),   # Still active
    ('test-site.org', '2019-06-01', '2023-06-0…
51 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",
…
17 0 Open
Strings & text easy

How to Validate Text Input in Python: A Simple Text Processor

A Python function that validates a text string by trimming whitespace, then returns a dictionary with character, word, and sentence counts.

text-validation strings input-checking
Python
def validate_text(text: str) -> dict:
    """Analyze a text string and return basic validation statistics."""
    stripped = text.strip()
    if not stripped:
        return {
            "valid": False,
            "reason": "Text is empty or only whitespace",
            "characters": 0,
            "words": 0,
    …
11 0 Open
Strings & text easy

How to Validate Text Strings in Python

Validate strings with a reusable helper that checks type, length limits, and empty string handling.

validation strings helper-function
Python
def is_valid_text(value, min_length=1, max_length=None, allow_empty=False):
    """
    Validate if a value is a string and meets length requirements.
    
    Args:
        value: The value to validate
        min_length: Minimum allowed length (default 1)
        max_length: Maximum allowed length (None = no limit)
…
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)}")
13 0 Open
Lists & loops easy

Check if List is Sorted Ascending in Python

Verify that a list is sorted in ascending order using the all() function and a generator expression.

lists sorted all
Python
def is_sorted_ascending(lst):
    return all(lst[i] <= lst[i + 1] for i in range(len(lst) - 1))

if __name__ == "__main__":
    test_lists = [
        [1, 2, 3, 4, 5],
        [1, 3, 2, 4, 5],
        [5, 4, 3, 2, 1],
        [1, 1, 2, 2, 3],
        [10],
        []
    ]
    for lst in test_lists:
        print(f"{l…
19 0 Open
Lists & loops easy

Extract Data by Type from a List in Python: Numbers and Strings

Loop through a mixed list to filter out numeric and string values into separate lists.

lists filtering type-checking
Python
def extract_numbers(items):
    """Extract all numeric values from a mixed list."""
    numbers = []
    for item in items:
        if isinstance(item, (int, float)) and not isinstance(item, bool):
            numbers.append(item)
    return numbers


def extract_strings(items):
    """Extract all string values from a…
14 0 Open
Lists & loops easy

How to Check if a List is Sorted in Descending Order in Python

This code defines a function that returns True if a given list is sorted in descending order, using a generator expression with all() to compare each adjacent pair.

sorted descending list
Python
def is_descending(lst):
    """Return True if list is sorted in descending order."""
    return all(lst[i] >= lst[i + 1] for i in range(len(lst) - 1))


if __name__ == "__main__":
    test_cases = [
        [5, 4, 3, 2, 1],
        [3, 3, 2, 1],
        [1, 2, 3],
        [10, 8, 9],
        []
    ]

    for case in …
13 0 Open
Lists & loops easy

How to Flatten a Deeply Nested List in Python Recursively

A recursive function that flattens arbitrarily deep nested lists into a single flat list using isinstance checks.

recursion flatten lists
Python
def flatten(nested_list):
    if not nested_list:
        return []
    if isinstance(nested_list[0], list):
        return flatten(nested_list[0]) + flatten(nested_list[1:])
    return [nested_list[0]] + flatten(nested_list[1:])


if __name__ == "__main__":
    data = [1, [2, [3, [4, [5]]]], [6, [7, [8, [9]]]], 10]
 …
13 0 Open
Lists & loops easy

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.

validation lists loops
Python
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…
16 0 Open
Lists & loops easy

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.

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

How to check list items by type and emptiness in Python

Loop through a list with enumerate(), classify each item as empty, number, or text, and print a formatted status for each element.

lists loops enumerate
Python
def check_data(data):
    """Check each item in a list and print whether it's valid."""
    for i, item in enumerate(data):
        if item is None or item == "":
            status = "empty"
        elif isinstance(item, (int, float)):
            status = "number"
        else:
            status = "text"
        pr…
14 0 Open
Functions & basics easy

How to Validate CLI Integer Option Within a Range in Python

Use argparse with integer type and bounds checking to validate a command-line option falls within a specified min-max range.

argparse cli validation
Python
import argparse

def main():
    parser = argparse.ArgumentParser(description="Validate an integer within a range.")
    parser.add_argument("--value", type=int, required=True, help="Integer to validate")
    parser.add_argument("--min", type=int, default=0, help="Minimum allowed value")
    parser.add_argument("--max…
13 0 Open
Functions & basics easy

How to Validate Function Arguments in Python

Shows how to manually check argument types and values in a Python function, raising clear TypeError and ValueError messages.

validation function arguments type hints
Python
def calculate_area(length: float, width: float) -> float:
    """Calculate the area of a rectangle with manual type validation."""
    if not isinstance(length, (int, float)) or isinstance(length, bool):
        raise TypeError(f"length must be a number, got {type(length).__name__}")
    if not isinstance(width, (int,…
13 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)}")
12 0 Open
Errors & debugging easy

How to Validate Input and Raise TypeError in Python

Define a function that checks its argument type and raises a TypeError early with a clear message when given a non-number.

type checking validation typeerror
Python
def validate_number(value):
    if not isinstance(value, (int, float)):
        raise TypeError(f"Expected a number, got {type(value).__name__}")
    return value * 2

if __name__ == "__main__":
    try:
        print(validate_number(5))
        print(validate_number("hello"))
    except TypeError as e:
        print(…
13 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.