Reference library

Python Code Samples

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

11 matches
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 …
14 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
Functions & basics easy

Compound interest calculator in Python

Compute future investment value with the compound interest formula and a readable year-by-year loop.

math finance functions
Python
def future_value(
    principal: float,
    annual_rate: float,
    years: int,
    compounds_per_year: int = 12,
) -> float:
    """Return balance after compound interest (rounded to cents)."""
    rate_per_period = annual_rate / compounds_per_year
    periods = compounds_per_year * years
    amount = principal * (1 …
53 0 Open
Errors & debugging easy

How to Assert an Invariant After a Complex Transformation in Python

Use assert to verify that a multi-step transformation preserves a mathematical invariant, catching regressions early.

assert debugging invariants
Python
def transform_value(value):
    """Apply several transformations to a value."""
    doubled = value * 2
    shifted = doubled + 10
    normalized = shifted / 2
    return int(normalized)

def assert_invariant(value):
    """Assert that the transformation preserves a key invariant."""
    original = value
    transform…
13 0 Open
Algorithms & data structures medium

Binary Search on Answer in Python: Koko Eating Bananas

Find the minimum eating speed so Koko finishes all banana piles within a given hour limit using binary search on the answer.

binary-search algorithms search
Python
import math

def min_eating_speed(piles, h):
    """Return minimum integer eating speed K so Koko finishes within h hours."""
    def hours_needed(speed):
        return sum(math.ceil(p / speed) for p in piles)

    low, high = 1, max(piles)
    while low < high:
        mid = (low + high) // 2
        if hours_needed…
15 0 Open
Algorithms & data structures easy

How to Compute Cosine Similarity Between Two Vectors in Python

This code calculates the cosine similarity between two numeric vectors using the dot product and Euclidean norms, returning a value between -1 and 1.

cosine similarity vectors math
Python
import math

def cosine_similarity(vec_a, vec_b):
    if len(vec_a) != len(vec_b):
        raise ValueError("Vectors must have the same length")
    
    dot_product = sum(a * b for a, b in zip(vec_a, vec_b))
    norm_a = math.sqrt(sum(a * a for a in vec_a))
    norm_b = math.sqrt(sum(b * b for b in vec_b))
    
    i…
13 0 Open
Algorithms & data structures easy

How to Generate an Arithmetic Progression List in Python

Generates a list of terms in an arithmetic progression using a list comprehension.

arithmetic list-comprehension sequences
Python
def generate_ap(start, difference, count):
    """Generate a list of n terms in an arithmetic progression."""
    return [start + i * difference for i in range(count)]


if __name__ == "__main__":
    ap = generate_ap(3, 5, 6)
    print(ap)
13 0 Open
Comprehensions & generators medium

How to Generate Primes with a Generator in Python

Generate prime numbers up to a limit using the Sieve of Eratosthenes wrapped in a generator expression for lazy evaluation.

generators sieve primes
Python
def prime_generator(limit):
    sieve = [True] * (limit + 1)
    sieve[0] = sieve[1] = False

    for i in range(2, int(limit ** 0.5) + 1):
        if sieve[i]:
            for j in range(i * i, limit + 1, i):
                sieve[j] = False

    return (num for num, is_prime in enumerate(sieve) if is_prime)


if __n…
14 0 Open
Comprehensions & generators easy

How to Generate a Collatz Sequence in Python

Generate the Collatz sequence for a given positive integer by repeatedly applying the 3n+1 rule until reaching 1.

collatz sequence loops
Python
def collatz_sequence(n):
    if n <= 0:
        raise ValueError("n must be a positive integer")
    sequence = [n]
    while n != 1:
        if n % 2 == 0:
            n = n // 2
        else:
            n = 3 * n + 1
        sequence.append(n)
    return sequence

if __name__ == "__main__":
    start = 7
    result…
13 0 Open
Testing & modern typing easy

Fix and Test a Regression Bug in Python with Unit Tests

This code implements a circle area function that raises ValueError for negative radii, then runs basic tests and a regression check for that edge case.

regression-testing unit-testing math
Python
import math

def calculate_area(radius):
    """Calculate the area of a circle given its radius."""
    if radius < 0:
        raise ValueError("Radius cannot be negative")
    return math.pi * radius ** 2

def main():
    test_cases = [0, 1, 2.5, 5, 10]
    
    print("Circle Area Calculator")
    print("-" * 30)
   …
16 0 Open
A/B testing & experimentation medium

How to Run a Fisher Exact Test in Python

Compute the two-sided Fisher exact test p-value for a 2x2 contingency table using pure Python and the math module.

statistics fisher-exact ab-testing
Python
from math import comb, factorial
from itertools import combinations


def hypergeometric_probability(a, b, c, d):
    """Probability of observing table [[a, b], [c, d]] under the null."""
    row1 = a + b
    row2 = c + d
    col1 = a + c
    col2 = b + d
    total = row1 + row2
    return (comb(row1, a) * comb(row2, …
17 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.