Science Oxford Logo

Random Colours

Instead of choosing the colours before you start, you can get the computer to choose for you.

At the very start of your program, add this line:

from random import randint

This imports a library, and tells Python that you want to use these new bits of code.


Every time you want the computer to choose you a colour, instead of typing a number in youself, write randint(0, 1023) - this says for it to choose a number between 0 and 1023.


For example, the code we wrote for the RGB LED would now look like this:

from microbit import *
from random import randint

red = pin0
green = pin1
blue = pin2

while True:
    red.write_analog(randint(0, 1023))
    green.write_analog(randint(0, 1023))
    blue.write_analog(randint(0, 1023))
    sleep(500)