pysnippets.numbers.clamp_number
Clamp a number to a range
clamp_number(value: float, low: float, high: float) -> float
Limit a value to an inclusive range, accepting the bounds in either order.
Keep a volume between 0 and 100, or a page number inside the document.
clamp_number.py✓ ruff · mypy --strict
def clamp_number(value: float, low: float, high: float) -> float:
"""Limit ``value`` to the range between ``low`` and ``high``, inclusive."""
low, high = min(low, high), max(low, high)
return max(low, min(value, high))- sort the bounds so callers can't get them backwards
examples✓ 3 doctests · 3.11–3.14
passed on Python 3.11 to 3.14: >>> clamp_number(2, 3, 5)3passed on Python 3.11 to 3.14: >>> clamp_number(1, -1, -5)-1passed on Python 3.11 to 3.14: >>> clamp_number(4.5, 0, 10)4.5Edit the function or the examples and run the doctests here, on Python 3.14. Python loads only when you click (about 7 MB, cached after the first time).
python 3.14 · in your browser
Loading Python 3.14 in your browser (≈7 MB, cached after the first time)…
Tab inserts four spaces. Press Escape, then Tab, to leave the editor. Control or Command plus Enter runs the examples.
How it works
min(value, high)caps the top;max(low, ...)lifts the bottom.- The bounds are sorted first, so
clamp_number(x, 10, 0)works too. - Ints stay ints and floats stay floats.
Complexity: O(1) time and space
- 3.11✓passes
- 3.12✓passes
- 3.13✓passes
- 3.14✓passes
Import
from pysnippets.numbers.clamp_number import clamp_numberNo dependencies: copy clamp_number.py into your project, or clone the repo.Adapted from clamp-number in 30-seconds-of-python by the 30 seconds of code contributors, CC BY 4.0. Changed: Typed; clearer names. Suggest an edit.