Random Color Generator with HLS Values

  • Share this:

Code introduction


This function accepts two parameters h and l between 0 and 1, uses these parameters to generate a random color, and prints its hexadecimal representation.


Technology Stack : Rich, random, colorsys

Code Type : Function

Code Difficulty : Intermediate


                
                    
def generate_random_color(arg1, arg2):
    from rich.console import Console
    from random import choice
    from colorsys import hls_to_rgb

    console = Console()
    if arg1 < 0 or arg1 > 1 or arg2 < 0 or arg2 > 1:
        console.print("Error: h and l values must be between 0 and 1.")
        return
    s = choice([0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9])
    color = hls_to_rgb(arg1, arg2, s)
    hex_color = '#{:02x}{:02x}{:02x}'.format(int(color[0]*255), int(color[1]*255), int(color[2]*255))
    console.print(f"Generated Color: {hex_color}")