Functions & basics
Reusable building blocks — parameters, returns, scope, and clear function design.
How to Compose Two Functions into a Single Callable in Python
Combine two Python functions into a single callable using a compose helper, then apply the chained call.
def add_one(x):
return x + 1
def double(x):
return x * 2
def compose(f, g):
return lambda x: f(g(x))
add_then_double = compose(double, add_one)
double_then_add = compose(add_one, double)
result1 = add_then_double(5)
result2 = double_then_add(5)
print(f"add_one then double(5) = {result1}")
print(f"doub…
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 _…
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.