Coders Packet

Generate Random Color Code in Python

By Vijay Viswha

This program code generates a random color code and hex value using random module in Python.

Hello, this program code generates a random color code using random module in Python. The random module is used for various functions that need the generation of random entities. The numbers created occur randomly and do not follow any type of algorithm for its generation.

We begin the program by importing the required module which is the random module. Now we can use the built-in module to perform actions using the built-in functions. Next up, we create a function 'random_color' with no arguments passed since the function requires no input from the user. Inside the function, we use the random.randint built-in function 3 times to create random values within the range of 0 to 255(inclusive of 255) for the color variables red, green, and blue.

Next, we assign the 3 generated values in the form of RGB color code format to a variable 'color_code'. And we also format color code to hexadecimal values. The 02 represents the number of digits, the capital X represents capital Hexa values, and # for format. The formatted value is assigned to a variable called 'hexa_value'. Then both the variables are returned.

Outside the function, we call the function and assign the returned values to their respective variables. Then both the variables are printed in the appropriate form.

 

Test output

Download Complete Code

Comments

No comments yet

Download Packet

Reviews Report

Submitted by Vijay Viswha (viswha19123)

Download packets of source code on Coders Packet