My code isn't working in the python rgb to hex converter!

I have tried the python coding challenge of the rgb to hex converter and here is my code.

def rgb_hex():
  invalid_msg = "Invalid value entered"
  red = int(input("Enter a red value: "))
  if red < 0 or red > 255:
  green = int(input("Enter a green value: "))
  if green < 0 or green > 255:
  blue = int(input("Enter a blue value: "))
  if blue < 0 or blue > 255:
  val = (red << 16) + (green << 8) + blue
def hex_rgb():
  hex_val = input("Enter the hexadecimal value: ")
  if len(hex_val) != 6:
    print("Invalid hexadecimal value")
    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:" , red , "Green:" , green , "Blue:" , blue)
def convert():
    while True:
      option = 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..."
      elif option == '2':
        print("Hex to RGB...")
      elif option == 'X' or option == 'x':

However, whenever I enter 1 or 2, the code just runs the print(“Error”) message, and gets me to enter a message again. And when I enter x it tells me that the name ‘x’ is not defined. Someone please help!

You’re missing some paraentheses with one of your print() functions. Fix that and try running it again and see what happens.

I tried to put parentheses around this but it still gave the same result.

I ran the code in Colab. I get this issue:

I fixed the issue and re-ran it. It works as intended, no?

But then once I enter values I get a Type error, “‘int’ object is not subscriptable”…on this line:
---> 17 print(str(hex(val[2::]))).upper()

So, how can we fix this?
Simply, this error occurs when you’re trying to access a variable that you’ve defined as an int but you’re trying to treat it like an array, when it cannot be.

See here for some hints:

Thank you very much. This fixed the problem!

1 Like