Use Python to Generate Random Color and Palette

Bruce Wen
7 min readFeb 28, 2024

It’s an interesting exploration of the colourful world.

Random Colored Balls Generated with Python

A color in the RGB color model is described by indicating how much of each of the red, green, and blue is included. The color is expressed as an RGB triplet (r,g,b), each component of which can vary from zero to a defined maximum value. If all the components are at zero the result is black; if all are at maximum, the result is the brightest representable white.

8-Bit RGB color is often used in software development. For example, Red color can be represented by #FF0000 .

To generate one random 8-Bit RGB color represented by hexadecimal is not a difficult job: I just need to generate 3 random integers in the range 0 to 255 and then convert them to hexadecimal.

The converted hexadecimal might be from 0 to f. To follow the format rule #RRGGBB , I created one small function to pad the place when needed.

def padding(num, target_length=2):
"""
Padding left for number to make it's string format length reaches the
target length.

This is mainly used to construct valid hex color number in R,G,B
position. Example, if the given num is a hex number 0xf and the
target length is 2, then the padding result is 0f.
"""
str_num = str(num)
target_length = target_length if target_length and…

--

--