Functions & basics
Reusable building blocks — parameters, returns, scope, and clear function design.
Build a Context Manager in Python with contextlib.contextmanager
Create a reusable context manager that safely opens and closes files using the contextlib contextmanager decorator.
from contextlib import contextmanager
@contextmanager
def managed_file(filename, mode='r'):
"""Context manager that opens and closes a file safely."""
file = open(filename, mode)
yield file
file.close()
if __name__ == "__main__":
# Write a sample file
with managed_file("sample.txt", "w") as f…
Calculate Time Difference Across Time Zones in Python
Compute the current time difference in hours between two time zones given their UTC offsets using Python's datetime and timezone modules.
from datetime import datetime, timezone, timedelta
def time_difference(from_tz_offset, to_tz_offset):
"""
Calculate time difference in hours between two time zones given their offsets from UTC.
Offsets are in hours (e.g., -5 for EST, +5.5 for IST).
"""
tz1 = timezone(timedelta(hours=from_tz_offset…
How to Build Partial Functions with functools.partial in Python
Create reusable partial functions that pre-fill arguments using functools.partial, like making square and cube functions from a general power function.
```python
from functools import partial
def power(base, exponent):
"""Calculate base raised to the exponent power."""
return base ** exponent
# Create partial functions for common powers
square = partial(power, exponent=2)
cube = partial(power, exponent=3)
if __name__ == "__main__":
squares = [square(x)…
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 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 Parse Command Line Arguments in Python with argparse
Build a CLI that accepts positional integers, an optional --sum flag, and a --verbose switch, all with Python's standard argparse library.
import argparse
def main():
parser = argparse.ArgumentParser(description='Process some integers.')
parser.add_argument('numbers', metavar='N', type=int, nargs='+',
help='an integer for the accumulator')
parser.add_argument('--sum', dest='accumulate', action='store_const',
…
How to Read Environment Variables in Python with Default Values
Retrieve an environment variable safely using os.getenv() with a fallback default when the variable is missing.
import os
database_url = os.getenv("DATABASE_URL", "postgresql://localhost:5432/mydb")
print(f"Database URL: {database_url}")
How to Use *args and **kwargs in Python Functions
Implement a variadic function that accepts arbitrary positional and keyword arguments using *args and **kwargs.
def display_info(title, *args, **kwargs):
"""Display positional and keyword arguments received."""
print(f"Title: {title}")
print(f"Additional positional args ({len(args)}):")
for i, arg in enumerate(args, 1):
print(f" {i}. {arg}")
print(f"Keyword args ({len(kwargs)}):")
for key, value…
How to Use Default Parameters in Python Functions
Define a Python function with default parameters and call it using positional and keyword arguments.
def greet(name, greeting="Hello", punctuation="!"):
"""Concatenate a greeting message with default parameters."""
return f"{greeting}, {name}{punctuation}"
if __name__ == "__main__":
print(greet("Alice")) # Uses both defaults
print(greet("Bob", "Hi")) # Uses default punctua…
How to Use Keyword-Only Arguments in Python Functions
Define Python functions with keyword-only arguments using the * separator to enforce clarity and prevent positional misuse.
def greet(name, *, greeting="Hello", punctuation="!"):
"""Greet someone with a customizable message using keyword-only arguments."""
message = f"{greeting}, {name}{punctuation}"
return message
if __name__ == "__main__":
# Basic call with only the positional argument
print(greet("Alice"))
# Al…
Write a Recursive Factorial Function in Python
Define a recursive factorial function that handles edge cases and returns the product of all positive integers up to n.
def factorial(n):
"""Return the factorial of n using recursion."""
if n < 0:
raise ValueError("Factorial is not defined for negative numbers")
if n == 0 or n == 1:
return 1
return n * factorial(n - 1)
if __name__ == "__main__":
print(factorial(5))
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.