1
def hex_to_rgb():
    hex = input("Input Hex Color Code. add space after every 2 letter, for example white - FF FF FF:")

    hexa = hex.split()
    values = {"0" : 0,"1" : 1,"2" : 2,"3":3,"4":4,"5":5,"6":6,"7":7,"8":8,"9" : 9, "A": 10, "B": 11, "C": 12, "D": 13, "E": 14, "F": 15}
    rgb_code = []

    red_input = str(hexa[0:1])  
    red_input2 = list(red_input)
    red_input3 =[]
    for item in red_input2:
        if item in values:
            red_input3.append(values[item])

    decimal = []
    red_input4 = sorted(red_input3)

    for number in red_input4:
        if red_input4.index(number) == 0:
            decimal.append(number*1)
        if red_input4.index(number) == 1:
            decimal.append(number*16)

    rgb_red = 0

    for redcode in decimal:
        rgb_red += redcode

the Code for reference. the code works when I input F5 for example, but when I input FF it breaks, since index() returns the lowest index for duplicates. is there any way to help this?

Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
  • 2
    You should look into ‘enumerate()’. It can give you the index of each item as you are iterating. – quamrana Jan 10 '21 at 10:40
  • It looks like you are converting hex to decimal. Did you know that ‘int()’ can take a base parameter? – quamrana Jan 10 '21 at 10:42
  • Are you trying to parse a hexadecimal number? Have you tried using `int(red_input4, 16)` instead of your loop? – mkrieger1 Jan 10 '21 at 10:43
  • Does this answer your question? [Accessing the index in 'for' loops?](https://stackoverflow.com/questions/522563/accessing-the-index-in-for-loops) – mkrieger1 Jan 10 '21 at 10:50
  • i have tried that int(red_input4, 16) it gives an error: "int() cant convert non-string with explicit base) – Knight Esquire Jan 10 '21 at 11:02
  • 1
    You'll have to update the question with examples of `red_input4` then. We're dancing in the dark at the moment. – quamrana Jan 10 '21 at 11:04
  • Again, as suggested, why are you not using `int`? Just do `red_input = int(hexa[0], 16)` – Tomerikoo Jan 10 '21 at 11:42

1 Answers1

1

You are doing alot of manual work for stuff that are already built-in. You can convert from hex to decimal with the int constructor:

def hex_to_rgb():
    rgb_hex = input("Input Hex Color Code. add space after every 2 letter, for example white - FF FF FF:")

    red, green, blue = [int(code, 16) for code in rgb_hex.split()]
Tomerikoo
  • 18,379
  • 16
  • 47
  • 61