How to Limit a Number to Be Within a Specified Range (Python)

How to limit a number to be within a specified range? (Python)

def clamp(n, minn, maxn):
return max(min(maxn, n), minn)

or functionally equivalent:

clamp = lambda n, minn, maxn: max(min(maxn, n), minn)

now, you use:

n = clamp(n, 7, 42)

or make it perfectly clear:

n = minn if n < minn else maxn if n > maxn else n

even clearer:

def clamp(n, minn, maxn):
if n < minn:
return minn
elif n > maxn:
return maxn
else:
return n

Limiting a number to a range

If you want to be fancy about it, this works nicely:

r, g, b = (min(255, max(0, c)) for c in (r, g, b))

Example:

In [1]: r, g, b = -1, 145, 289

In [2]: r, g, b = (min(255, max(0, c)) for c in (r, g, b))

In [3]: r, g, b
Out[3]: (0, 145, 255)

Python make a number loop within a range

Just figured it out.

def loop(n, minn, maxn):

while n > maxn:
n = n - (maxn - minn)
while n < minn:
n = n + (maxn - minn)

return n

I think that should work for most cases, including negative numbers and ranges.

Limiting user input to a range in Python

Use a while loop to keep asking them for input until you receive something you consider valid:

shift = 0
while 1 > shift or 26 < shift:
try:
# Swap raw_input for input in Python 3.x
shift = int(raw_input("Please enter your shift (1 - 26) : "))
except ValueError:
# Remember, print is a function in 3.x
print "That wasn't an integer :("

You'll also want to have a try-except block around the int() call, in case you get a ValueError (if they type a for example).

Note if you use Python 2.x, you'll want to use raw_input() instead of input(). The latter will attempt to interpret the input as Python code - that can potentially be very bad.

How to clamp an integer to some range?

This is pretty clear, actually. Many folks learn it quickly. You can use a comment to help them.

new_index = max(0, min(new_index, len(mylist)-1))


Related Topics



Leave a reply



Submit