Generate random hex color code in python

Python -- Posted on May 2, 2023

Is a Python script that generates random hexadecimal color codes and prints them repeatedly with a one-second delay. The get_random_color() function generates a random color by randomly selecting characters from the hexadecimal range and returning the color in the format '#RRGGBB'.

Here's a step-by-step explanation of the code:

  1. The random and time modules are imported to use their functions in the script.
  2. The get_random_color() function is defined to generate a random color. It selects random characters from the letters string, which contains hexadecimal digits (0-9 and A-F). The loop runs six times (representing the RRGGBB components of the color), and each time it appends a randomly selected character to the color variable.
  3. The while True loop runs indefinitely. It generates a new random color using the get_random_color() function, prints the color, and then waits for one second using time.sleep(1) before repeating the process.

This script is useful for generating random colors and can be used for various purposes, such as in graphical applications, visualization, or even for fun in a Python environment. If you run this script, you will see a continuous stream of random color codes being printed to the console with one-second intervals between them.

                import random
import time

def get_random_color():
    letters = '0123456789ABCDEF'
    color = '#'
    for i in range(6):
        color += letters[random.randint(0, 15)]
    return color

while True:
    color = get_random_color()

Related Posts