0

I don't understand how this statement is creating a color in Python. I would really appreciate any clarification. I see that it must be substituting in the random numbers but that is as far as I get.

rgb = ('#%02X%02X%02X' % (random.randint(0,255),random.randint(0,255),random.randint(0,255)))
KimGWC
  • 1
  • 1
    If you're just wondering how python knows how to construct the string from the given parameters, see the [String Formatting](https://docs.python.org/2/library/stdtypes.html#string-formatting-operations) docs. – glibdud Feb 20 '17 at 14:38
  • 1
    `%02X` is hex representation of integer that you generate with `random.randomint(0,255)` – zipa Feb 20 '17 at 14:42
  • 1
    With this, you will generate a string representing a color in hexadecimal. Each `%02X`part will be a value for Red, Green or Blue (RGB). The `02` part tells python to use at least 2 digits and to use zeros to pad it to length. The `X` part tells python to use upper-case hexadecimal. Finally, the `%` allow to subsitute those parts with randomly generated values, between `0` and `255` (`00` and `FF` in hex). I think it was too quickly marked as duplicate because the question is not explicitly asking ONLY how the formatting works. – iFlo Feb 20 '17 at 14:43
  • Thank you. It is very clear now! – KimGWC Feb 21 '17 at 02:55

1 Answers1

0

The use of % is the substitute for the variable. For example, if I have the following code,

name = input('Enter your name')
age = input('How old are you?'
print('Hello, %, you are % years old' % name, age)
exit(0)

the % next to "Hello," would be replaced with the value of the variable "name" (As decided by the "% name" which follows the string.

Enter your name:  Harvey
Hello, Harvey, you are 18 years old

In your case, the % would be a series of random numbers, which are used to generate the hex colour.

Harvey Fletcher
  • 1,167
  • 1
  • 9
  • 22