First lines of MicroPython
Python for the micro:bit is called MicroPython. Every micro:bit program starts with the line from microbit import *, which loads the library of micro:bit commands; the star means “everything in it”. The command display.scroll("Hi") moves text across the lights. Text must be inside quotation marks, which makes it a string. The command display.show(Image.HEART) shows a picture, and picture names are written in capital letters. MicroPython syntax is strict about capital letters, brackets, dots and quotation marks, so one wrong letter, such as Image.heart, stops the line from working. The command sleep(1000) pauses the program for 1000 milliseconds, which is 1 second. To try a finished program on the real board, an adult connects it with a USB cable and flashes the program onto it.
1from microbit import * 2display.scroll("Hi") 3display.show(Image.HEART)
scrolls Hi, then shows a heart
1from microbit import * 2display.show(Image.SQUARE) 3sleep(1000) 4display.show(Image.SQUARE_SMALL)
big square for 1 second, then a small square
| Line | Does it work? | Why |
|---|---|---|
| display.scroll("Hi") | yes | text is in double quotes |
| display.scroll('Hi') | yes | text is in single quotes |
| display.scroll(Hi) | no | Hi is not in quotes, so it is not text |
| display.scroll("Hi') | no | the quotes do not match |
| Line | Works? |
|---|---|
| display.show(Image.YES) | yes |
| display.show(Image.yes) | no – image names are capitals |
| Display.show(Image.YES) | no – display starts with a small d |
| display.shwo(Image.YES) | no – misspelt command |
Syntax detective (no computer). On paper write six lines of MicroPython: three that are correct and three that each have one mistake, such as a missing quotation mark or a small letter in a picture name. Swap with a friend. They mark the mistakes in red and say which rule was broken. Then write a program that scrolls your first name and then shows a picture of your choice from this list: HEART, YES, NO, SQUARE, HOUSE. If you have a computer or tablet, an adult can help you type it into a micro:bit editor and run it.
1from microbit import * 2display.scroll("Go") 3sleep(2000) 4display.show(Image.YES)
1from microbit import * 2display.scrol("Hi") 3display.show(Image.Heart) 4display.scroll(Bye)
1from microbit import * 2display.show(Image.YES) 3___(___) 4display.show(Image.___)