Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Most Pythonic way to fit a variable to a range? [duplicate]

Tags:

python

Is there a more Pythonic way to achieve this:

result = #...real value from elsewhere
max_value = 1
min_value = 0
if result > max_value:
    result = max_value
elif result < min_value:
    result = min_value
return result

Not sure how to explain it in words so I hope it's clear. Thanks

like image 347
trim Avatar asked Feb 14 '23 10:02

trim


1 Answers

You can use the min and max functions:

result = min(max_value, max(min_value, result))
like image 67
GWW Avatar answered Feb 16 '23 01:02

GWW