I finished the project and it behaves OK I guess, with one exception.
I did not receive any errors. However, when I will choose a RGB value which has red = 0, I will not get the first two digits of the hexadecimal code:
Cyan has the RGB value (0,255,255)
The hexadecimal value printed by the program should be #00FFFF.
Unfortunately, the printed value is actually FFFF , without the double 0s in the beginning.
def rgb_hex(): invalid_msg = "The wrong value was inserted" red = int(raw_input("Enter the Red (R) value: ")) if red < 0 or red > 255: print invalid_msg return green = int(raw_input("Enter the Green (G) value: ")) if green < 0 or green > 255: print invalid_msg return blue = int(raw_input("Enter the Blue (B) value: ")) if blue < 0 or blue > 255: print invalid_msg return val = (red << 16) + (green << 8) + blue print "%s" % (hex(val)[2:]).upper() def hex_rgb(): hex_val = raw_input("Enter the color (six hexadecimal digits): ") if len(hex_val) != 6 : print "Invalid hexidecimal value. Try again." 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 "Red: %s Green: %s Blue: %s" % (red, green, blue) def convert(): while True: option = raw_input("Enter 1 to convert RGB to HEX. Enter 2 to convert HEX to RGB. 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()
To the code above, I would add the following validation rule:
if red == 0: print "#" + "00" + "%s" % (hex(val)[2:]).upper() else: print "#" + "%s" % (hex(val)[2:]).upper()
Do you think there is a better or a more refined way to achieve this? Do you think that this might have a negative impact?