Skip to content

活動

Odd and even numbers

中等級數 | MakeCode, Python | LED 螢幕, 按鈕 | 數字和位置值, 算法, 選擇, 除法

步驟1:製作

它是什麼?

Play a maths game with your BBC micro:bit! Program it to choose a random number from 1 to 100. You can decide if the number is odd or even, and then use your micro:bit to test if you are right.

這兩支影片為您示範了製作內容和編碼方法:

您將會學到

You’ll learn how to turn a simple mathematical algorithm into code, how to use selection in computer programs, and how to divide a number and use its remainder.

If you want the learning to focus on maths skills rather than coding, then the ready-made code is available to download right away. Click on 'Open in MakeCode' or download the hex file below.

運作方式

  • This program is based on an algorithm for working out if a number is odd or even. The algorithm says: divide the number by two and if the remainder is 0, the number is even. Otherwise the number is odd.
  • When you press button A, the program picks a random number between 1 and 100 and shows it on the micro:bit’s LED display. (The program picks a random number rather than the same number each time to make the game fun to play more than once.)
  • When you press button B, the program divides the number by 2 and works out its remainder. 
  • The program then uses an ‘if… else’ statement. If the remainder is 0, the word ‘even’ appears on the micro:bit’s LED display. Else, it shows the word ‘odd’.
  • When different things can happen based on different conditions in a computer program like this, it is known as selection. You'll find key terms like selection explained in our vocabulary posters and glossary.

你需要的東西

  • micro:bit (或,MakeCode simulator)
  • MakeCode 或, Python 編輯器
  • 電池組(選配)

步驟2:編碼

1from microbit import *
2import random
3
4# An error could appear if you press button B without pressing button A first.
5# If the variable ‘number’ has not been assigned.
6# To work around this, the value of 101 is assigned to the variable 'number' 
7# at the start of the program. When you press button B the program tests 
8# first to see if the value of ‘number’ is 101 - if it is, it shows a helpful message.
9
10number = 101
11
12while True:
13    if button_a.was_pressed():
14        number = random.randint(1, 100)
15        display.scroll(number)   
16    if button_b.was_pressed():
17        if number == 101:
18            display.scroll('no number chosen yet') 
19        elif number%2 == 0:
20            display.scroll('even')   
21        else:
22            display.scroll('odd') 

步驟3:進階

  • Find a way to show the random number chosen more than once.
  • If you press button B before pressing button A, no random number will have been chosen and the LED display will show the word 'even'. Can you adapt the code so this doesn't happen? Look at the Python version of the program for an idea of how.
  • Adapt the program to explore other factors of numbers, for example, if 3 is a factor of 100.