The snippet library.
Small, practical examples. Search by task or narrow things down below.
Choose between two branches
Python: Use if and else to handle an available or empty stock count.
Python✓ Tested
Clamp a numeric value between bounds
Python: Combine min and max for a closed interval when lower is no greater than upper.
Python✓ Tested
Clean up a temporary directory automatically
Python: Use TemporaryDirectory as a context manager so cleanup also happens after exceptions.
Python✓ Tested
Collect independent asynchronous results
Python: Use asyncio.gather to await multiple coroutines while preserving input order.
Python✓ Tested
Combine text with a name
Python: Construct a greeting from a fixed prefix and a stored name.
Python✓ Tested
Compare a value with a limit
Python: Turn a comparison into a readable yes or no result.
Python✓ Tested
Compare floating-point calculations with tolerance
Python: Use isclose instead of exact equality for results affected by floating-point rounding.
Python✓ Tested
Compare Unicode text without case
Python: Casefold handles more Unicode case mappings than lower for caseless comparison.
Python✓ Tested
Convert a duration to hours and minutes
Python: Use divmod to split nonnegative whole seconds into display components.
Python✓ Tested
Convert a Unix timestamp to aware UTC
Python: Supply timezone.utc so the result does not depend on the machine time zone.
Python✓ Tested
Convert an aware datetime to another offset
Python: Use astimezone for conversion; replacing tzinfo alone does not convert an instant.
Python✓ Tested
Convert hexadecimal text to bytes
Python: Use bytes.fromhex for a readable byte representation and hex for the reverse conversion.
Python✓ Tested