4

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

trim
  • 209
  • 3
  • 9

4 Answers4

6

You can use the min and max functions:

result = min(max_value, max(min_value, result))
GWW
  • 43,129
  • 11
  • 115
  • 108
  • 4
    as one of the answers in the [duplicate](http://stackoverflow.com/questions/4092528/how-to-clamp-an-integer-to-some-range-in-python) points out, this is much easier to read if you wrap it in its own function e.g. `clamp(value, min_, max_)` – Adam Smith Mar 21 '14 at 17:45
1

Here's one option I like:

result = max_value if result > max_value else result
result = min_value if result < min_value else result
Mike Bell
  • 1,356
  • 11
  • 9
1

All you need is the sorted method

result = sorted((min_value,result, max_value))[1]
flakes
  • 21,558
  • 8
  • 41
  • 88
0

do you really need this part?

elif result < min_value:
    result = min_value

wouldnt this do just aswell

result = #...real value from elsewhere
max_value = 1
min_value = 0
if result >= max_value:
    result = max_value
else:
    result = min_value
return result
matthew_1098
  • 41
  • 1
  • 6
  • 1
    No because you forgot to check the case of in the middle! There are three options min, actual, max. All you have is min, max – flakes Mar 21 '14 at 17:50
  • ah sorry thought id put the >= in will edit – matthew_1098 Mar 21 '14 at 17:58
  • This still only has two end possibilities for `result`. You have an `if` with a regular `else` meaning that one of two paths will always be chosen. IE) `result = max_value` or `result = min_value` will always be called ^ ^ – flakes Mar 21 '14 at 18:05
  • By OP writing `elif` there are actually **three** paths,`result = max_value` or `result = min_value` or result stays the same – flakes Mar 21 '14 at 18:06