Python Code
Samples
Easy snippets you can copy, study, and run in the browser editor.
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.
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 …
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.
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)}")
Compound interest calculator in Python
Compute future investment value with the compound interest formula and a readable year-by-year loop.
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 …
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.
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…
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.
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…
How to Generate an Arithmetic Progression List in Python
Generates a list of terms in an arithmetic progression using a list comprehension.
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)
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.
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…
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.
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)
…
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
- Pick a topic section — strings, lists, files, functions, and more
- Open a sample, read How it works, and copy the code block
- 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.