How to generate a random RGBA color and opacity in Python

2 Answers

0 votes
import random

"""
Generate a random RGBA color string.
Produces full‑range RGB values and a floating‑point opacity.
"""

# Generate a random integer in the range [0, 255]
def random_channel() -> int:
    return random.randint(0, 255)

# Generate a random opacity in the range [0, 1]
def random_opacity() -> float:
    return random.random()  # full precision floating‑point

# Create a random RGBA color string
def random_rgba() -> str:
    r = random_channel()
    g = random_channel()
    b = random_channel()
    a = random_opacity()

    # Format as rgba(r, g, b, a) with two decimal places
    return f"rgba({r}, {g}, {b}, {a:.2f})"

# Example usage
color: str = random_rgba()
print(color)


"""
run:

rgba(183, 30, 193, 0.82)

"""

 



answered Aug 25 by avibootz
0 votes
import random

"""
Generate a random RGBA color string.
Uses Python's built‑in random module and concise expressions.
"""

def random_rgba() -> str:
    # Random RGB channels in the full 0–255 range
    r = random.randint(0, 255)
    g = random.randint(0, 255)
    b = random.randint(0, 255)

    # Random opacity in the 0–1 range (full floating‑point precision)
    a = random.random()

    # Format with two decimal places for readability
    return f"rgba({r}, {g}, {b}, {a:.2f})"


# Example usage
color = random_rgba()
print(color)


"""
run:

rgba(195, 66, 200, 0.96)

"""

 



answered Aug 25 by avibootz
...