Skip to content

User guide

Python guide

How the micro:bit works with Python, one of the world's most popular programming languages

Why Python?

Python is a text-based language used widely in education, and by professional programmers in areas like data science and machine learning.

Supported by a huge community of educators and computing experts, Python makes a great next step after block coding and is a perfect introduction to text-based programming.

The micro:bit Python editor

Our online Python editor is designed with teachers and learners in mind: you can easily enlarge the text size for sharing on a large screen or whiteboard, download projects as Python text files or .HEX files ready to flash onto a micro:bit. It also works with micro:bit classroom.

Using a modern Chrome browser you can quickly and easily download programs direct to your micro:bit using webUSB, and interact directly with your micro:bit using your computer keyboard using the Serial feature. You can also add Python modules to extend your programs and easily use accessories.

Hello, World!

Let's start with the basics - making some words and a picture appear on your micro:bit's display. Go to the Python editor and you’ll see this program:

1
2
3
4
5
6
7
8
# Add your Python code here. E.g.
from microbit import *


while True:
    display.scroll('Hello, World!')
    display.show(Image.HEART)
    sleep(2000)

Flash it to your micro:bit by downloading a hex file and transferring it, or flash it by webUSB, and see words and pictures appear on your micro:bit.

You need to be very precise when coding in text-based languages, and Python is no exception. The spaces at the start of lines 6, 7 and 8 are important. These are called indentations, made from four space characters (or one press of the TAB key.)

You’ll notice that Python programs often use a while True: statement. This is an infinite loop like the forever block in MakeCode or Scratch. The instructions indented after while True: form part of the loop: your micro:bit will keep carrying out those instructions as long as it has power. Any instructions after while True: that are not indented won't run until the loop has finished.

Images

As well as showing a heart icon, you can use lots more built-in images with Python. Try HAPPY, DUCK or GHOST, or make your own like this example. Try different numbers from 0 to 9 to make each LED darker or brighter.

1
2
3
4
5
6
7
from microbit import *

display.show(Image('00300:'
                   '03630:'
                   '36963:'
                   '03630:'
                   '00300'))

Light up your micro:bit with love by showing a heart

Make your micro:bit’s heart beat using loops

Buttons

Unlike MakeCode, Python on the micro:bit doesn’t have event blocks like ‘on button A pressed’. Instead, we use the infinite while True: loop to keep checking if a button has been pressed. (Actually, MakeCode programs do the same thing when they run on your micro:bit, but MakeCode hides the infinite loop from you when you’re writing your code.)

Can you guess what this program does? Try it out!

1
2
3
4
5
6
7
from microbit import *

while True:
    if button_a.is_pressed():
        display.show(Image.HAPPY)
    if button_b.is_pressed():
        display.show(Image.SAD)

Use your micro:bit to express how you’re feeling

Use buttons to play different tunes

Gestures

The micro:bit has an accelerometer input sensor built-in which measures physical forces. You can use to make things happen when you move your micro:bit in certain ways, such as when you shake it, drop it, turn it on its side, face up or face down. These movements are called gestures.

1
2
3
4
5
6
7
8
9
10
11
12
from microbit import *

while True:
    if accelerometer.was_gesture('shake'):
        display.show(Image.SILLY)
        sleep(2000)
    if accelerometer.was_gesture('face up'):
        display.show(Image.HAPPY)
    if accelerometer.was_gesture('left'):
        display.show('<')
    if accelerometer.was_gesture('right'):
        display.show('>')

Shake your micro:bit to make random numbers

Make your own step counter with a micro:bit

Accelerometer readings

You can also get more accurate readings of forces from the micro:bit’s accelerometer in 3 dimensions. This program works as a kind of spirit level, showing a dash if it’s level, or showing arrows to tell you which way it’s leaning if it’s not flat on your desk. It does this by measuring forces just in the x-axis:

1
2
3
4
5
6
7
8
9
from microbit import *

while True:
    reading = accelerometer.get_x()
    if reading > 20:
        display.show(">")
    elif reading < -20:
        display.show("<")
    else: display.show("-")
micro:bit showing X axis going across the front, Y axis going down and up, Z axis going back to front

Random numbers

You can add more functions to Python on your micro:bit by importing modules. This program imports the random module so we can make a simple random number generator like dice:

1
2
3
4
5
6
from microbit import *
import random

while True:
    if accelerometer.was_gesture('shake'):
        display.show(random.randint(1, 6))
Python docs on random numbers

Shake your micro:bit to make random numbers

Compass

Your micro:bit has a input sensor for measuring magnetic fields, which you can use as a compass. This project tells you, once you’ve calibrated it by playing a little game, what compass bearing the top of your micro:bit is pointing towards.

1
2
3
4
5
6
from microbit import *
compass.calibrate()

while True:
    if button_a.was_pressed():
        display.scroll(str(compass.heading()))

Create a simple compass to show which way is North

Make your own micro:bit wireless door alarm

Light sensor

The LED display on the front of your micro:bit can also detect light, acting as a sensor input as well as an output. Try this simple nightlight project: shine a light on your micro:bit, then cover it or turn out the lights and you should see the display light up.

1
2
3
4
5
6
7
from microbit import *

while True:
    if display.read_light_level() < 100:
        display.show(Image.HEART)
    else: display.clear()
    sleep(2000)

Create a light that turns on when it’s dark

Make an alarm that goes off when lights go on

Temperature

The micro:bit’s processor contains a temperature sensor which you can use in your programs. It’s a useful approximation of the temperature around your micro:bit. This program shows how warm or cold your micro:bit is in °C when you press button A:

1
2
3
4
5
from microbit import *

while True:
    if button_a.was_pressed():
        display.scroll(temperature())
Learn about the temperature sensor

Make a simple thermometer with your micro:bit

Radio

Two or more micro:bits can communicate wirelessly using the radio module. Flash this program on to two micro:bits and see what happens when you shake each in turn:

1
2
3
4
5
6
7
8
9
10
11
12
from microbit import *
import radio
radio.config(group=23)
radio.on()

while True:
    message = radio.receive()
    if message:
        display.show(Image.DUCK)
    if accelerometer.was_gesture('shake'):
        display.clear()
        radio.send('duck')

Music

headphones connected to pin 0 and GND pin of micro:bit using crocodile clip leads

Attach headphones to pin 0 and GND on your micro:bit and you can use it to make noise and play music. There are many more built-in tunes to enjoy, try ODE, BLUES or BIRTHDAY - or compose your own.

1
2
3
4
5
6
from microbit import *
import music

while True:
    if button_a.was_pressed():
        music.play(music.NYAN)

Use buttons to play different tunes

Speech

Your micro:bit can talk when you import the speech module. Connect headphones to pin 0 and GND pins and try this program. How could you add speech to improve a project or make it more accessible?

1
2
3
4
from microbit import *
import speech

speech.say('Hello, World')
Python docs on speech

Input/output Pins

The strip of golden 'teeth' at the bottom of your micro:bit allow you to connect it to electronics such as switches, sensors, lights, motors - and even other micro:bits.

Networking

You can communicate securely over wires with two micro:bits (no-one can snoop on your radio messages!) and learn about computer networking.

Nominet have also written a Python version of their book Networking with the micro:bit which covers wired and wireless networking.

Python docs on networking

Adding Python modules

You can access the micro:bit's Python file system to add Python modules to extend your programs or make using accessories easier.

Learn how to add files and modules

Serial (REPL)

The Serial REPL (Read-Evaluate-Print-Loop) feature lets you type Python commands on your computer and run them immediately on your micro:bit without the need to flash a whole program. Connect using webUSB, flash any Python program onto your micro:bit then click on the 'Open Serial' button, and click on the Ctrl-C button.

Type import love into the REPL, press enter and see what happens to your micro:bit!

The Serial feature is also helpful for debugging programs as you can use it to read any Python error messages from your micro:bit. Switch to the Serial mode and reset your micro:bit and you'll see any error messages on your computer screen as well as scrolling across the micro:bit's display.

Find our more about Serial

Next steps

Always experiment, always explore, always learn!

Once you get used to the concepts in this guide, read the full Python documentation to learn how to take things further.

Full micro:bit Python documentation