Randomly generate a Hex Colour code and its contrasting colour using Python I am attempting to generate a new colour and its contrasting colour with this python script.

I plan to try to make a web app that is different every time it is loaded (i.e. background and text colour)

I am wondering if there is a better and more efficient way to do this?

Here is my code:

import random

values = ['0','1','2','3','4','5','6','7','8','9','10','11','12','13','14','15']
value_dict = [['A','10'],['B','11'],['C','12'],['D','13'],['E','14'],['F','15']]
start = "#"

def contrastcolour(colour):
    if colour[0] == '#':
        colour = colour[1:]
    rgb = (colour[0:2], colour[2:4], colour[4:6])
    comp = ['%02X' % (255 - int(a, 16)) for a in rgb]
    return ''.join(comp)

def startcolour():
    colour = "#"
    for i in range(6):
        x = values[random.randint(0,len(values)-1)]

        for thing in value_dict:
            if x == thing[1]:
                x = thing[0]
        colour = colour + x
    return colour

base = startcolour()
contrast = start + contrastcolour(base)

print("The colours: {0}".format([base, contrast]))


The sample output is: 

The colours: ['#2EF7F3', '#D1080C']
Review


Globals should be ALL_CAPS


start



=> START
Accumulation: Loop variables that are not explicitly used within the loop block should be replaced by _ , as is standard Python style. 


for i in range(6):



You don't use the i later on, so the convention is to use _ for a dummy variable.

=> for _ in range(6)
The name of the variable value_dict implies it's a dict (Python's built-in dictionary type) but it's implemented as a list.


value_dict = [['A','10'],['B','11'],['C','12'],['D','13'],['E','14'],['F','15']]
...
for thing in value_dict:
    if x == thing[1]:
        x = thing[0]



You could change this to use an actual dict like this:

val_dict = {'10' : 'A', '11' : 'B', '12' : 'C', '13' : 'D', '14' : 'E', '15' : 'F'}
...

if x in val_dict:
    x = val_dict[x]

Or better yet why not immediately convert to an hexadecimal using hex?
Check your naming. Don't be overly generic.

values #
thing  # Each of these could literally be anything
x      #

colour = colour + x
can be rewritten as colour += x
Use spaces around the comma: a,b => a, b
Use a if __name__ == '__main__' guard




Essentially your startcolour() can be rewritten as a one-liner

from random import randint
_HEX = list('0123456789ABCDEF')
...
def startcolour():
    return '#' + ''.join(_HEX[randint(0, len(_HEX)-1)] for _ in range(6))