Now that your micro:bit scripts can receive values from the terminal, let’s put those values to work in an app. This first example is a countdown timer that allows you to set the number of seconds in the countdown.
# countdown_timer.py from microbit import * sleep(1000) text = input("Enter seconds to count down: ") value = int(text) message = input("Enter message after countdown: ") while value >= 0: print(value) sleep(1000) value = value - 1 print(message)
First, the script captures the text representation of a number you type into the terminal. This gets converted into an int value that the script can store and use for counting repetitions. This int value gets stored in the value variable.
text = input("Enter seconds to count down: ") value = int(text)
The text you type in response to the message prompt gets stored as a string of characters in the message variable, which is a string.
message = input("Enter message after countdown: ")
Since the value variable now stores an int variable, it can use it to control how many times this while loop repeats:
while value >= 0: print(value) sleep(1000) value = value - 1
After the while loop is done, your custom message gets displayed.
print(message)
This is another way of using text and values from the terminal — a calculator app.
# calculator.py from microbit import * sleep(1000) while True: text = input("Enter first integer a: ") a = int(text) op = input("Enter operation + - * /: ") text = input("Enter second integer b: ") b = int(text) if op == "+": c = a + b elif op == "-": c = a - b elif op == "*": c = a * b elif op == "/": c = a / b print("a", op, "b = ", c) print(" ")
Interval timers repeatedly count down the same amount of time, and are used to control the amount of time one has to repeatedly run a sprint or swim a lap, including rest. They are also used in stretching after a workout so that each stretch is only done for a fixed amount of time.
It helps to break this program into steps. Here is some pseudo-code that you can work from to build the program:
Outer loop always repeats
Get the countdown seconds and store in an int variable.
Get the reps and store in an int variable.
while reps > 0
copy countdown seconds to a temporary variable.
Print start interval message
while temporary variable > 0
Print temporary variable
Wait a second
Subtract 1 from temporary variable.
Subtract 1 from reps
Print done with set
Hint: Make the indentation levels in the pseudo code match the indentation levels in your code.