1

Is it possible to shorten the if statements below ?

if r < 0: r = 0
elif r > 255: r = 255
if g < 0: g = 0 
elif g > 255: g = 255
if b < 0: b = 0
elif b > 255: b = 255
asked Apr 27, 2020 at 14:08

3 Answers 3

1

This is what you call as clamping. Create a clamp function as below:

def clamp(n, smallest, largest): 
 return max(smallest, min(n, largest))

Now you can call it on your variables as

r = clamp(r, 0, 255)
answered Apr 27, 2020 at 14:11
Sign up to request clarification or add additional context in comments.

Comments

0

You can use min and max.

r = min(max(r, 0), 255)

The inner expression makes sure r is at least 0. The outer expression makes sure it's no more than 255.

answered Apr 27, 2020 at 14:10

Comments

0

To answer your question on shorting the if statement code you provided and not providing an alternative solution to getting the same result as your if statement.

def rgb_8bit_trunc(r,g,b):
 print("Input: r:{}, g:{}, b:{}".format(r,g,b))
 r = 0 if r < 0 else r if r < 255 else 255
 g = 0 if g < 0 else g if g < 255 else 255
 b = 0 if b < 0 else b if b < 255 else 255
 print("Output: r:{}, g:{}, b:{}".format(r,g,b))
rgb_8bit_trunc(256,256,256)
rgb_8bit_trunc(-1,-1,-1)

Each ternary conditional operator is equivalent to the if statement code below where 'value' may be any of your RGB variables.

if value < 255:
 if value < 0:
 value = 0
 else:
 value
else:
 value = 255
answered Apr 27, 2020 at 14:47

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.