0

Assuming that I have three variables r, g, b. If any of these variables are < 0 or > 255, they are to be rounded to 0 and 255 respectively.

My unsophisticated knowledge of python would tell me to utilise a bunch of if-statements, which I think would be time-consuming and unnecessary. Is there any other method of doing this?

aayush
  • 157
  • 7
  • 1
    On second thought, I could perhaps use a for-loop, but I await answers. – aayush Aug 05 '21 at 14:23
  • Maybe this helps: https://stackoverflow.com/questions/5996881/how-to-limit-a-number-to-be-within-a-specified-range-python – Cynja Aug 05 '21 at 14:27
  • 1
    How about `r = max(0,min(r,255))` etc? That does coercion into the range 0..255 as part of the test, and avoids the `if` statements you don't want. – BoarGules Aug 05 '21 at 14:31

4 Answers4

2
if 255 > variable > 0:

You can simplify mathematical parameters somewhat like this.

Dan Curry
  • 149
  • 8
  • 1
    Thanks, this works. However, does this really solve my purpose considering I will still have to ascertain whether the variable was ```> 255``` or ```< 0```, to round it to the appropriate figure? – aayush Aug 05 '21 at 14:31
1
rgb = (0,255,125)
check = [(0<=value<=255) for value in rgb]
print(sum(check)==3)
# -> True

This checks for whether all values fits the critera.

Jett Chen
  • 382
  • 2
  • 8
0

If you are using numpy, and you have an array of your values you can clamp your values with a single line of code:

import numpy as np

a = np.array([ ... values ...])
a[a > 255] = 255
a[a < 0 ] = 0

numpy has optimizations for operations on vectors, so for large amount of values numpy might be also faster.

user107511
  • 772
  • 3
  • 23
-1
if r in range(0, 255):
    # code

You could see if you like this syntax

Peter Kapteyn
  • 354
  • 1
  • 13