# 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:
print(invalid_msg)
return
green = int(input("Enter a green value: "))
if green < 0 or green > 255:
print(invalid_msg)
return
blue = int(input("Enter a blue value: "))
if blue < 0 or blue > 255:
print(invalid_msg)
return
val = (red << 16) + (green << 8) + blue
print(str(hex(val[2::]))).upper()
def hex_rgb():
hex_val = input("Enter the hexadecimal value: ")
if len(hex_val) != 6:
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:" , 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..."
rgb_hex()
elif option == '2':
print("Hex to RGB...")
hex_rgb()
elif option == 'X' or option == 'x':
break
else:
print("Error")
convert()
``````

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:
https://www.stechies.com/typeerror-int-object-is-not-subscriptable/

Thank you very much. This fixed the problem!

1 Like

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