0

I get some user input and if they pick a value outside of a given interval I want to set the value to the edge value. I can do it like this:

if input > upper_limit:
    input = upper_limit
elif input < lower_limit:
    input = lower_limit

It feels like there should be a nicer way of doing this but I can't figure out how. Do you have any suggestions?

Eli
  • 156
  • 8

2 Answers2

2

You can use the min and max functions:

input = min(input, upper_limit)
input = max(input, lower_limit)

or just

input = max(min(input, upper_limit), lower_limit)
Kemp
  • 3,467
  • 1
  • 18
  • 27
0

You can do it the functional way:

i = upper_limit if  i > upper_limit else lower_limit if i <lower_limit else i

btw, better to not name your vars as input, because you are shadowing a built-in function.

Assem
  • 11,574
  • 5
  • 59
  • 97