![]() |
Help with conversion program - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: Help with conversion program (/thread-38006.html) |
Help with conversion program - uwl - Aug-19-2022 I have errors in my code, it is for converting RGB to Hex in python. def color(RGB): if RGB > 255: RGB = 255 elif RGB < 0: RGB = 0 RGB = hex(RGB)[2:].upper() if len(RGB)<2: RGB = '0'+RGB return RGB def rgb(r, g, b): return color(r)+color(g)+color(b)It shows for line 7. the following is thrown: Does anyone have recommendations to help me fix this program?I already tried adding str() to len(RGB)<2: with no successes.
RE: Help with conversion program - deanhystad - Aug-19-2022 Your indentation was wrong on line 6. This was only called if RGB < 0 RGB = hex(RGB)[2:].upper()Use f'string formatting. It will do the zero fill and upper case for you. In the code below, "02X" Says convert to upper case hexadecimal (X) and pad with 0 (0) to a width of 2 characters (2). I also prefer using min and max for clipping numbers to a range. def rgb2hex(r, g, b, prefix=""): clipped = (max(0, min(255, c)) for c in (r, g, b)) return prefix + "".join((f"{c:02X}" for c in clipped)) print(rgb2hex(184, 7, 280, "#"))
|