Sorting Hat

"""
    Harry Potter Sorting Hat

    Copyright (c) 2016 Various Authors

    MIT  Licence

"""

# import microbit and random modules
from microbit import *
import random

# create a list of strings called HOUSES
HOUSES   = ["Gryffindor",
            "Slytherin",
            "Ravenclaw",
            "Hufflepuff",
           ]

# create an endless loop waiting for button_a to be pressed
while True:
    if button_a.is_pressed():
        display.scroll(random.choice(HOUSES))
    sleep(100)

How it Works

Create a List of Hogwarts Houses

The names are loaded into a list. In the example above the list is created over 5 lines making it easier to read. A list can be created on one line too:

HOUSES   = ["Gryffindor", "Slytherin", "Ravenclaw", "Hufflepuff",]

A list contains “objects” (the Python way to say “whatsists”, “thingamabobs” or “doodahs”). An object can be any type of thing. In this example the objects are strings (of characters) so the value is surrounded by quotation marks like this: "Gryffindor".

random.choice(HOUSES)

When button_a is pressed, the micro:bit’s display scrolls a random house (or in code: display.scroll(random.choice(HOUSES))). It uses the random.choice method to randomly choose an object in the HOUSES list. How simple is that?

random.choice requires the random module. This is not included by defaults so we need to import it:

import microbit from *
import random
What to import and when

So when should you import modules? It’s very simple to understand. You will only ever need to import 3 other modules: neopixel, random and music:

import neopixel: Import this to connect to a neopixel. Neopixels are very cool and a fun way to create digital art!

import random: Import this to use random numbers. Anything beginning random. needs this module.

import music: Import this to make a sound on your micro:bit. Anything beginning music. will need this module.

RULE: you only need to import a module if your code needs random numbers, makes a sound or uses a neopixel. Most of the time just use from microbit import *

What is sleep(100)?

while True: puts the micro:bit into an infinite loop. This means the micro:bit repeats the program’s loop as fast as it can. The program runs so fast that the processor cannot keep up and the micro:bit crashes.

sleep(100) makes the processor do nothing for 100 milliseconds (or .1 of a second). This slows down the program so the processor can keep up. The processor in your micro:bit is so fast that microbit.sleep(1) is enough of a wait.

Computer or phone crashes are often caused by badly written code that creates an infinite loop!

Share On
Facebook Twitter Google Plus

Published: December 23, 2016 Updated: December 23, 2016

Sorting Hat

Pick a random item from a list when the microbit button is pressed.

Jez Dean
Teacher