Want to add new condition to check Hexadecimal code

#1

Hi everyone! I was practicing with the RGB-HEX converter. After a few trial runs, I found out that the code only tests the validity of the hexadecimal input based on the length of the input (6-digit). However, what if we input an invalid 6-digits info (such as 123ABK, AJFKLD, etc.) ?

I have done some research on the internet to found out the code that will check whether users have input a hexadecimal color with characters only ranging from A to F. And i found out this solution:

import re
str = ‘#ffffff’ # Your Hex

match = re.search(r’^#(?:[0-9a-fA-F]{3}){1,2}\$’, str)

if match:
print ‘Hex is valid’

else:
print ‘Hex is not valid’

Can anyone explain this to me or maybe give me a solution for my code? For example. if we input ‘A1B2CH’, the console will display ‘invalid values entered’.

``````
def rgb_hex():
invalid_msg = "Invalid values entered"
red = int(raw_input("Enter red (R) value:  "))
if (red < 0 or red > 255):
print invalid_msg
return
green = int(raw_input("Enter Green (G) value:  "))
if (green < 0 or green > 255):
print invalid_msg
return
blue = int(raw_input("Enter Blue (B) value:  "))
if (blue < 0 or blue > 255):
print invalid_msg
return
val = (red << 16) + (green << 8) + blue
print "Convert to Hexadecimal color:  %s" % (hex(val)[2:]).upper()

def hex_rgb():
invalid_msg = "Invalid values entered"
hex_val = raw_input("Enter Hexadecimal value:  ")
if len(hex_val) != 6:
print invalid_msg
return
else:
hex_val = int(hex_val, 16)
two_hex_digits = 2 ** 8
blue = hex_val % two_hex_digits
hex_val = hex_val >> 8
green = hex_val % two_hex_digits
hex_val = hex_val >> 8
red = hex_val % two_hex_digits
print "Convert to RGB color: %d%d%d" % (red, green, blue)

def convert():
while True:
option = raw_input("Enter 1 to convert RGB to HEX. Enter 2 to convert HEX to RFB. Enter X to Exit:  ")
if option == "1":
print "RGB to Hex. . ."
rgb_hex()
elif option == "2":
print "Hex to RGB. . ."
hex_rgb()
elif option == "X":
break
else:
print "Error"
convert()

``````

#2

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.