Functions & basics
Reusable building blocks — parameters, returns, scope, and clear function design.
How to Create a Higher-Order Function in Python (Apply Twice)
This code defines a higher-order function that takes another function and a value, then applies the function twice to the value and returns the result.
def apply_twice(func, value):
return func(func(value))
def add_ten(x):
return x + 10
def square(x):
return x ** 2
if __name__ == "__main__":
print(apply_twice(add_ten, 5))
print(apply_twice(square, 3))
How to Create an Iterator Class with Dunder Methods in Python
A minimal Counter class implementing __iter__ and __next__ to act as a self-iterating iterator, yielding numbers from start to end-1.
class Counter:
def __init__(self, start=0, end=5):
self.current = start
self.end = end
def __iter__(self):
return self
def __next__(self):
if self.current >= self.end:
raise StopIteration
value = self.current
self.current += 1
return val…
How to Print Colored Text in Python with ANSI Codes
Define a small Colors class and a colored() helper to print styled terminal text using ANSI escape codes.
class Colors:
RESET = "\033[0m"
RED = "\033[31m"
GREEN = "\033[32m"
YELLOW = "\033[33m"
BLUE = "\033[34m"
MAGENTA = "\033[35m"
CYAN = "\033[36m"
WHITE = "\033[37m"
BOLD = "\033[1m"
UNDERLINE = "\033[4m"
def colored(text, color):
return f"{color}{text}{Colors.RESET}"
if _…
How to Write a Context Manager Class in Python
Define a class with __enter__ and __exit__ to manage file resources safely using the with statement.
class FileReader:
def __init__(self, filename, mode="r"):
self.filename = filename
self.mode = mode
self.file = None
def __enter__(self):
self.file = open(self.filename, self.mode)
return self.file
def __exit__(self, exc_type, exc_val, exc_tb):
if self.file…
Browse by section
Each section groups closely related Python snippets.
Functions & basics — Python code examples
What you will find here
This page collects functions & basics snippets — short, copy-ready Python you can paste into our free online IDE and run without installing anything. Each sample includes a plain-English explanation and the full source code.
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.