What's the best way of writing a constrain function? or is there already a builtin python function that does this?
Option 1:
def constrain(val, min_val, max_val):
    if val < min_val: return min_val
    if val > max_val: return max_val
    return val
Option 2:
def constrain(val, min_val, max_val):
    if val < min_val: 
        val = min_val
    elif val > max_val: 
        val = max_val
    return val
                I do not know if this is the more "pythonic", but you can use built-in min() and max() like this:
def constrain(val, min_val, max_val):
    return min(max_val, max(min_val, val))
                        In case you need to do this for a lot of numbers (arrays full of them), you should probably be using Numpy, which has a built-in clip function. For simple Python programs, go with Delgan's answer.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With