Reference library

Python Code Samples

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

86 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…
52 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 Detect PII in Documents Using Python

Use regex patterns to automatically detect emails, phone numbers, SSNs, and credit card numbers in text documents.

pii regex data-privacy
Python
import re
from typing import List, Dict

def detect_pii(text: str) -> Dict[str, List[str]]:
    patterns = {
        "email": r"[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}",
        "phone": r"\(?\d{3}\)?[-.\s]?\d{3}[-.\s]?\d{4}",
        "ssn": r"\b\d{3}-\d{2}-\d{4}\b",
        "credit_card": r"\b\d{4}[- ]?\d{4}[-…
50 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 Mask Credit Card Middle Digits in Python

Mask the middle digits of credit card numbers in a string, keeping only the first 8 and last 4 digits, using regular expressions.

regex string-manipulation security
Python
import re

def mask_credit_card(text: str) -> str:
    pattern = re.compile(r'(\d{4}[-\s]?)(\d{4}[-\s]?)(\d{4}[-\s]?)(\d{4})')
    return pattern.sub(lambda m: m.group(1) + m.group(2) + '****' + m.group(4), text)

if __name__ == "__main__":
    sample = "Card: 1234-5678-9012-3456 and 1111 2222 3333 4444"
    print(mas…
12 0 Open
Errors & debugging medium

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.

logging redaction security
Python
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…
13 0 Open
Files & data easy

Audit File Permissions Across a Project in Python

Walks through every file and directory in a project tree and prints POSIX permissions plus owner UID.

file permissions os.walk audit
Python
import os
import stat
from pathlib import Path

def audit_file_permissions(project_root):
    """Walk through project_root and print path, owner, and permissions for every file."""
    results = []
    for root, dirs, files in os.walk(project_root):
        for name in files + dirs:
            full_path = os.path.joi…
56 0 Open
Files & data medium

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.

encryption security passwords
Python
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…
46 0 Open
Files & data medium

Encrypt and Decrypt Files Using Python

Encrypt and decrypt files using the cryptography library's Fernet symmetric encryption.

encryption decryption fernet
Python
import os
from pathlib import Path
from cryptography.fernet import Fernet

def generate_key(key_file: Path) -> bytes:
    key = Fernet.generate_key()
    key_file.write_bytes(key)
    return key

def load_key(key_file: Path) -> bytes:
    return key_file.read_bytes()

def encrypt_file(input_path: Path, key: bytes, out…
56 0 Open
Files & data easy

How to Compute File SHA256 Hash with hashlib in Python

Compute the SHA256 hash of a file by reading it in chunks with hashlib and Path.open.

hashlib sha256 file-hash
Python
import hashlib
from pathlib import Path

def sha256_file(file_path: Path) -> str:
    sha256_hash = hashlib.sha256()
    with file_path.open("rb") as f:
        for chunk in iter(lambda: f.read(4096), b""):
            sha256_hash.update(chunk)
    return sha256_hash.hexdigest()

if __name__ == "__main__":
    demo_fi…
15 0 Open
Files & data medium

How to Load Pickle Files Safely in Python

This code demonstrates how to load pickle files safely in Python by using a restricted unpickler that only allows specific, trusted classes, preventing arbitrary code execution from untrusted pickles.

pickle security serialization
Python
import pickle

# Default pickle.load is unsafe: it executes arbitrary code when unpickling.
class Unsafe:
    def __reduce__(self):
        return (eval, ("open('/tmp/pickle_demo.txt', 'w').write('pwned')",))

# Create a malicious payload (simulating untrusted source)
malicious_data = pickle.dumps(Unsafe())

# Safe ap…
13 0 Open
Files & data easy

Parameterize SQL queries in Python to prevent SQL injection

Safely fetch users from a SQLite database using parameterized queries to prevent SQL injection attacks.

sqlite3 sql injection parameterized query
Python
import sqlite3

def get_users_by_name(name):
    """Fetch users safely using parameterized query."""
    conn = sqlite3.connect(':memory:')
    cursor = conn.cursor()
    
    # Create sample table and data
    cursor.execute('CREATE TABLE users (id INTEGER, name TEXT)')
    cursor.executemany('INSERT INTO users (name…
14 0 Open
Algorithms & data structures medium

How to Detect Hardcoded Secrets in Python Source Code

A Python utility that scans source code for common hardcoded secrets like API keys, passwords, tokens, and AWS credentials using regex patterns.

secrets regex security
Python
import re

def detect_secrets(text):
    """Detect potential hardcoded secrets in source code."""
    patterns = {
        'api_key': r'(?i)(api[_-]?key|apikey)\s*[=:]\s*["\']([^"\']+)["\']',
        'password': r'(?i)(password|passwd)\s*[=:]\s*["\']([^"\']+)["\']',
        'token': r'(?i)(\b(token|secret)\b)\s*[=:]\s…
42 0 Open
AI & LLM integration patterns easy

Demonstrate Prompt Injection Bypass in Python

Simulate why naive system prompt filters fail against prompt injection with casing and spacing variations.

prompt-injection llm-security demo
Python
# Demonstrate why system prompts can be bypassed by simulated user input
# This demo shows a naive filter being ignored via prompt injection

def process_user_message(message, system_rules):
    """Simulate an AI that follows system rules but gets tricked."""
    # Claim to check system rules
    for rule in system_ru…
14 0 Open
AI & LLM integration patterns medium

How to Detect Prompt Injection in Python

Implements a regex-based heuristic in Python to flag common prompt injection attempts before sending input to an LLM.

prompt-injection regex llm-security
Python
import re

def contains_prompt_injection(user_input: str) -> bool:
    # Directives to ignore previous instructions or act as system
    ignore_patterns = [
        r"\bignore\s+(all\s+)?previous\s+instructions\b",
        r"\bdisregard\s+(all\s+)?previous\s+instructions\b",
        r"\bdon'?t\s+follow\s+(any\s+)?inst…
13 0 Open
AI & LLM integration patterns easy

How to Filter Blocked Words in Python

Scans input text against a moderation blocklist, returning blocked terms and their counts.

moderation blocklist security
Python
MODERATION_BLOCKLIST = {"spam", "scam", "fraud", "phishing", "malware", "abuse"}

def scan_text(text: str) -> dict:
    normalized = text.lower()
    words = normalized.replace(".", " ").replace(",", " ").replace("!", " ").replace("?", " ").split()
    
    found_terms = []
    for word in words:
        if word in MO…
11 0 Open
Automation & scripting medium

Find Sensitive Information in Log Files with Python

Scan log files for emails, IP addresses, API keys, and passwords using regular expressions in Python.

regex security log-analysis
Python
import re
import os
from pathlib import Path

def find_sensitive_info(log_path):
    """Scans log files for patterns like emails, IPs, API keys, and passwords."""
    patterns = {
        'Email': r'[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}',
        'IP Address': r'\b(?:\d{1,3}\.){3}\d{1,3}\b',
        'API Key'…
35 0 Open
Automation & scripting easy

Generate Strong Random Passwords with Custom Rules in Python

Build a configurable password generator using Python's secrets module that lets you toggle lowercase, uppercase, digits, and punctuation.

password secrets security
Python
import secrets
import string

def generate_password(length=16, use_lower=True, use_upper=True, use_digits=True, use_punct=True):
    pool = ''
    if use_lower:
        pool += string.ascii_lowercase
    if use_upper:
        pool += string.ascii_uppercase
    if use_digits:
        pool += string.digits
    if use_pu…
36 0 Open
Automation & scripting medium

Generate Strong SSH Keys and Save Them Securely with Python

Generate a 4096-bit RSA SSH key pair using Python's cryptography library and save both private and public keys with restricted file permissions.

ssh key-generation cryptography
Python
import os
import stat
from pathlib import Path
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric import rsa
from cryptography.hazmat.backends import default_backend

def generate_ssh_keypair(key_path: str = "id_rsa", passphrase: str = None):
    """Generate a 4096-…
34 0 Open
Automation & scripting medium

How to Detect Recently Installed Software in Python

Uses subprocess to call pip and parse package metadata to list recently installed Python packages.

pip subprocess automation
Python
import subprocess
import sys
from datetime import datetime, timedelta

def detect_recently_installed(days=7):
    """Detect recently installed software packages."""
    recent_packages = []
    cutoff_date = datetime.now() - timedelta(days=days)
    
    try:
        # For pip-installed packages (Python packages)
    …
33 0 Open
Automation & scripting easy

How to Quarantine Suspicious Files in Python

Move files with suspicious extensions to a quarantine folder using pathlib and shutil for safe isolation.

file-organization security automation
Python
import shutil
import os
from pathlib import Path

def quarantine_files(source_dir, quarantine_dir, suspicious_extensions):
    """
    Move files with suspicious extensions to a quarantine folder.
    Returns list of moved files.
    """
    source_path = Path(source_dir)
    quarantine_path = Path(quarantine_dir)
   …
10 0 Open
Automation & scripting medium

How to Scan Configuration Files for Security Issues in Python

Automatically scan configuration files for common security mistakes using regex rules in Python.

security config regex
Python
import re
import os
from pathlib import Path

SECURITY_RULES = [
    (r'^#\s*INSECURE_', 'Insecure comment starts with # INSECURE_'),
    (r'password\s*=\s*("|\\\')?[^"\\\'"\s]+("|\\\')?$', 'Hardcoded password'),
    (r'debug\s*=\s*True', 'Debug mode enabled'),
    (r'[Pp]ermit[Rr]ootLogin\s+yes', 'PermitRootLogin ena…
46 0 Open
Automation & scripting easy

How to Scan Files Against a Malware Hash List in Python

Compare a file's SHA-256 hash against a known malware hash set and report whether it's clean or infected.

hashlib file-scanning security
Python
import hashlib
from pathlib import Path

# Mock file content (in real usage, read from disk)
MOCK_FILE_CONTENT = b"print('hello world')"

KNOWN_MALWARE_HASHES = {
    "8d969eef6ecad3c29a3a629280e686cf0c3f5d5a86aff3ca12020c923adc6c92",
    "5e884898da28047151d0e56f8dc6292773603d0d6aabbdd62a11ef721d1542d8",
}

def sha25…
13 0 Open
Automation & scripting medium

How to Scan Open Ports on a Host with Python

A Python function that uses socket.connect_ex to check for open TCP ports on a given host within a range and returns a list of open ports.

socket network port-scanning
Python
import socket

def scan_ports(host, start_port, end_port):
    open_ports = []
    for port in range(start_port, end_port + 1):
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        sock.settimeout(0.5)
        result = sock.connect_ex((host, port))
        if result == 0:
            open_ports.app…
41 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.