Reference library

Python Code Samples

Easy snippets you can copy, study, and run in the browser editor.

162 matches
Strings & text easy

Find Data From a String in Python: Stats, Clean, Keywords

Three helper functions for beginners: compute character/word/sentence stats, normalize whitespace and case, and extract unique sorted keywords from a string.

strings text-processing keywords
Python
def get_text_stats(text):
    """Return basic statistics about a string."""
    words = text.split()
    sentences = text.replace('!', '.').replace('?', '.').split('.')
    sentences = [s for s in sentences if s.strip()]
    return {
        'characters': len(text),
        'words': len(words),
        'sentences': le…
14 0 Open
Strings & text easy

How to Center Text in a Fixed-Width Banner in Python

Centers any text inside a fixed-width banner using fill characters and computed padding.

strings formatting text-alignment
Python
def center_text_banner(text, width=40, fill_char="="):
    """Center text within a fixed-width banner."""
    if len(text) >= width:
        return text
    
    total_padding = width - len(text)
    left_padding = total_padding // 2
    right_padding = total_padding - left_padding
    
    banner_line = fill_char * w…
14 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 Round Numbers with f-strings in Python

Round numbers directly inside f-string expressions using the built-in round() function for clean, readable output formatting.

f-string rounding formatting
Python
def main():
    # Values to format with expression-based rounding
    price = 19.995
    tax_rate = 0.0825
    distance = 1234.56789

    # Round inside the f-string expression using round()
    print(f"Price rounded to cents: ${round(price, 2)}")

    # Combine rounding with arithmetic inside the expression
    total…
12 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 wrap long text to a specified width in Python

Uses Python's textwrap.fill to wrap a long string to a specified width at word boundaries, preserving readability in console output or logs.

textwrap text wrapping formatting
Python
import textwrap

text = """This is a long piece of text that definitely exceeds the width limit
if we try to print it on a single line without any wrapping applied."""

wrapped = textwrap.fill(text, width=40)

print(wrapped)
11 0 Open
Strings & text easy

Python String Helper Functions for Beginners

A set of beginner-friendly Python functions that count words, reverse text, convert to title case, strip punctuation, and compute character frequency from a string.

strings text-processing word-count
Python
def count_words(text):
    """Count the number of words in a string."""
    return len(text.split())


def reverse_text(text):
    """Reverse the entire string."""
    return text[::-1]


def title_case(text):
    """Capitalize the first letter of each word."""
    return text.title()


def remove_punctuation(text):
 …
14 0 Open
Strings & text easy

String helpers in Python: stats, reverse, and remove vowels

Three beginner-friendly Python functions compute text statistics, reverse word order, and strip vowels from a string.

string-manipulation text-stats vowel-removal
Python
def text_stats(text: str) -> dict:
    """Return basic statistics for a given text string."""
    words = text.split()
    return {
        "characters": len(text),
        "words": len(words),
        "sentences": text.count(".") + text.count("!") + text.count("?"),
        "uppercase": sum(1 for c in text if c.isupp…
14 0 Open
Strings & text easy

Validate email format with regex in Python

A Python function using a regex pattern to validate simple email formats, returning True or False for each input.

regex email validation
Python
import re

def is_valid_email(email):
    pattern = r'^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$'
    return bool(re.match(pattern, email))

if __name__ == "__main__":
    test_emails = [
        "user@example.com",
        "first.last@sub.domain.org",
        "invalid-email",
        "user@.com",
        "user@…
12 0 Open
Lists & loops easy

Generate Data Helper for Beginners in Python

Define two functions that create a random list of integers and then compute basic summary statistics like count, total, average, maximum, and minimum using simple loops.

random loops lists
Python
from random import randint

def build_dataset(size: int, max_val: int) -> list[int]:
    data = []
    for _ in range(size):
        data.append(randint(1, max_val))
    return data

def summarize(data: list[int]) -> dict[str, float]:
    total = 0
    maximum = data[0]
    minimum = data[0]
    for value in data:
   …
12 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 Calculate the Average of a List of Numbers in Python

Compute the arithmetic mean of a numeric list using Python's built-in sum() and len() functions, returning 0.0 for an empty list.

average mean sum
Python
def calculate_average(numbers):
    if not numbers:
        return 0.0
    return sum(numbers) / len(numbers)

if __name__ == "__main__":
    sample_numbers = [10, 20, 30, 40, 50]
    result = calculate_average(sample_numbers)
    print(f"Average: {result}")
13 0 Open
Lists & loops easy

How to Compute Percentile Value from Sorted List in Python

Compute any percentile value from a sorted list using linear interpolation between ranks.

percentile statistics interpolation
Python
def percentile(sorted_data, percentile_value):
    """Return the value below which `percentile_value`% of data falls."""
    if not sorted_data:
        raise ValueError("Cannot compute percentile of empty list")
    if not 0 <= percentile_value <= 100:
        raise ValueError("Percentile must be between 0 and 100")
…
16 0 Open
Lists & loops easy

How to Compute Sliding Window Sum of Size k in Python

Compute the sum of every contiguous subarray of a fixed size k using an efficient O(n) sliding window technique.

sliding-window list sum
Python
def sliding_window_sum(nums, k):
    """Return a list of sums for each contiguous subarray of size k."""
    if not nums or k <= 0 or k > len(nums):
        return []
    
    result = []
    window_sum = sum(nums[:k])
    result.append(window_sum)
    
    for i in range(k, len(nums)):
        window_sum += nums[i] -…
13 0 Open
Lists & loops easy

How to Compute a Moving Average in Python

This code computes the moving average over a numeric list using an efficient sliding window sum, avoiding recomputation of each window.

moving-average sliding-window lists
Python
def moving_average(data, window_size):
    """
    Compute the moving average over a numeric list.
    
    Args:
        data: List of numeric values
        window_size: Size of the sliding window (positive integer)
    
    Returns:
        List of moving averages, each representing the mean of a window
    """
   …
14 0 Open
Lists & loops easy

How to Filter Even Numbers and Square Them in Python

Create two beginner-friendly helper functions that filter even numbers and compute squares of a number list using loops, then print the results along with the sum and average.

loops filtering math
Python
def get_even_numbers(numbers):
    evens = []
    for num in numbers:
        if num % 2 == 0:
            evens.append(num)
    return evens

def get_squares(numbers):
    squares = []
    for num in numbers:
        squares.append(num ** 2)
    return squares

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

even_numbers …
15 0 Open
Lists & loops easy

How to Find the Median of a List in Python

Compute the median of an unsorted numeric list using the statistics module in Python.

median statistics lists
Python
import statistics

def median_of_list(numbers):
    return statistics.median(numbers)

if __name__ == "__main__":
    sample = [7, 3, 1, 4, 9, 2, 8]
    print(median_of_list(sample))
12 0 Open
Lists & loops easy

How to Flatten One Level of a Nested List in Python

Flattens exactly one level of a nested list by extending the output with each inner list and appending non-list items.

flatten nested list list comprehension
Python
def flatten_one_level(nested_list):
    """Flatten one level of a nested list."""
    flattened = []
    for item in nested_list:
        if isinstance(item, list):
            flattened.extend(item)
        else:
            flattened.append(item)
    return flattened

if __name__ == "__main__":
    # Example with mi…
15 0 Open
Lists & loops easy

How to Parse a Comma String into a List of Integers in Python

Converts a comma-separated string into a list of integers, handling spaces and empty inputs.

csv parsing list-comprehension
Python
def parse_csv_to_ints(text: str) -> list[int]:
    """Parse a comma-separated string into a list of integers."""
    if not text.strip():
        return []
    return [int(part.strip()) for part in text.split(",") if part.strip()]

if __name__ == "__main__":
    sample = "10, 20, 30, 40, 50"
    result = parse_csv_to_…
13 0 Open
Lists & loops easy

How to Standardize a List with Z-Score Normalization in Python

This code computes the z-score for each number in a list, standardizing the data to have zero mean and unit variance using the statistics module.

z-score standardization statistics
Python
import statistics

def z_score_normalize(values):
    """Standardize a list of numbers using z-score normalization."""
    if not values or len(values) < 2:
        raise ValueError("Need at least 2 values for meaningful z-score normalization")
    
    mean = statistics.mean(values)
    std_dev = statistics.stdev(val…
14 0 Open
Lists & loops easy

How to Summarize a List of Numbers in Python

Loop over a list of numbers to compute total, count, average, min, and max, then return them in a dictionary.

lists loops statistics
Python
def summarize_numbers(numbers):
    """Return a dict with basic stats for a list of numbers."""
    total = 0
    count = 0
    smallest = numbers[0]
    largest = numbers[0]

    for num in numbers:
        total += num
        count += 1
        if num < smallest:
            smallest = num
        if num > largest:…
16 0 Open
Lists & loops easy

How to summarize and transform lists in Python

Compute count, sum, min, max, and average for a list and multiply each element by a factor using simple loops and built-in functions.

lists loops statistics
Python
def summarize(data):
    """Return a summary of a list: count, sum, min, max, average."""
    count = len(data)
    total = sum(data)
    minimum = min(data)
    maximum = max(data)
    average = total / count if count else 0
    return count, total, minimum, maximum, average


def multiply_elements(data, factor=2):
 …
13 0 Open
Lists & loops easy

How to unzip a list of pairs into two lists in Python

Split a list of (a, b) tuples into two separate lists by iterating with a for loop and appending each element to its own output list.

lists tuples loops
Python
def unzip(pairs):
    """Split a list of (a, b) pairs into two separate lists."""
    if not pairs:
        return [], []
    
    firsts = []
    seconds = []
    for a, b in pairs:
        firsts.append(a)
        seconds.append(b)
    
    return firsts, seconds


if __name__ == "__main__":
    pairs = [(1, 'a'), (…
14 0 Open
Lists & loops easy

Pairwise Adjacent Differences in a Python List

Computes the absolute differences between each pair of adjacent elements in a list using a concise list comprehension.

list-comprehension differences absolute-value
Python
def adjacent_differences(nums):
    """Return list of absolute differences between adjacent elements."""
    return [abs(nums[i] - nums[i + 1]) for i in range(len(nums) - 1)]


if __name__ == "__main__":
    sample = [3, 7, 2, 9, 5]
    diffs = adjacent_differences(sample)
    print("Original list:", sample)
    print…
14 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.