Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth
Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

42,844 questions

55,671 answers

573 users

How to generate a random color in HEX format with Python

4 Answers

0 votes
import random

color = ["#"+''.join([random.choice('0123456789ABCDEF') for j in range(6)])]

print(color)




'''
run:

['#B6CB3A']

'''

 



answered Apr 27, 2021 by avibootz
0 votes
import random
 
hex =  "#%06x" % random.randint(0, 0xFFFFFF) 
 
print(hex);
 
 
'''
run:
 
#7ef1f3
 
'''

 



answered 2 days ago by avibootz
0 votes
import random
 
def generate_random_hex_color():
    hex_chars = "0123456789ABCDEF"
    hex_code = ''.join(random.choice(hex_chars) for _ in range(6))
    
    return hex_code
     
 
print(f"Random HEX Color: #{generate_random_hex_color()}")

 
'''
run:
 
Random HEX Color: #09DE82
 
'''

 



answered 2 days ago by avibootz
0 votes
"""
Generate a random color in HEX format (#RRGGBB).
This program demonstrates how numbers and bits are used
to produce a valid 24‑bit color value.
"""

import random

def random_color_int():
    """
    Create a 24‑bit random integer (0x000000–0xFFFFFF).
    random.random() gives a floating‑point number in [0, 1),
    so multiplying by 0x1000000 (2**24) gives a range of 24 bits.
    """
    # 24 bits → values from 0 to 16,777,215 (0xFFFFFF)
    return int(random.random() * 0x1000000)


def int_to_hex_color(value):
    """
    Convert a 24‑bit integer into a hex color string.
    format(value, "06x") ensures the hex string is always 6 characters.
    """
    # Convert number → hex string (e.g., "3fa2c")
    hex_str = format(value, "06x")

    # Add the leading "#"
    return f"#{hex_str}"


def generate_random_hex_color():
    """
    Produce a random hex color by combining the two functions.
    """
    value = random_color_int()      # 24‑bit random number
    hex_color = int_to_hex_color(value)  # Convert to #RRGGBB
    
    return value, hex_color


# Run the program
value, hex_color = generate_random_hex_color()
print("Random 24‑bit value:", value)
print("Hex color:", hex_color)


"""
run:

Random 24‑bit value: 9225261
Hex color: #8cc42d

"""

 



answered 2 days ago by avibootz
...