首页 > 解决方案 > 为什么此代码在没有任何输入的情况下在启动时显示“A”?

问题描述

这是一个用于 microbit 的莫尔斯电码翻译器,但它在开始时显示“A”

from microbit import *
morse={'.-': 'A', '-...': 'B', '-.-.': 'C', '-..': 'D', '.': 'E', '..-.': 'F', '--.': 'G', '....': 'H', '..': 'I', '.---': 'J', '-.-': 'K', '.-..': 'L', '--': 'M', '-.': 'N', '---': 'O', '.--.': 'P', '--.-': 'Q', '.-.': 'R', '...': 'S', '-': 'T', '..-': 'U', '...-': 'V', '.--': 'W', '-..-': 'X', '-.--': 'Y', '--..': 'Z', '.----': '1', '..---': '2', '...--': '3', '....-': '4', '.....': '5', '-....': '6', '--...': '7', '---..': '8', '----.': '9', '-----': '0', '--..--': ', ', '.-.-.-': '.', '..--..': '?', '-..-.': '/', '-....-': '-', '-.--.': '(', '-.--.-': ')'}

message=''
while True:
    morseChr=''
    if button_a.is_pressed:
        morseChr+='.'
    if button_b.is_pressed:
        morseChr+='-'
    if button_a.is_pressed and button_b.is_pressed:
        message+=morse[morseChr]
        display.show(message)
        sleep(1000*len(message))
        display.clear()

我希望它将按钮按下转换为消息,但它只显示“A”

标签: pythonmicropythonbbc-microbit

解决方案


您当前的逻辑有两个问题:

首先,每当您同时按 A 和 B 时,.-都会将其添加到您的消息中。为避免这种情况,else if请先使用 an 并移动 A 和 B 案例(因为这应该比 A 或 B 具有更高的优先级)。

其次,您实际上不能在消息中添加除 A 之外的任何其他字符,因为您morseChar在每个循环中都被重置为空字符串。您需要将变量移出循环以跟踪先前的输入。

此外, is_pressed 是根据 microbit 文档的功能。

生成的代码如下所示:

message=''
morseChr=''

while True:
    if button_a.is_pressed() and button_b.is_pressed():

        # First check if the entered char is actually valid
        if morseChr not in morse:
            morseChr='' # reset chars to avoid being stuck here endlessly
            # maybe also give feedback to the user that the morse code was invalid
            continue

        # add the char to the message
        message += morse[morseChr]
        morseChr=''

        display.show(message)
        sleep(1000*len(message))
        display.clear()

    elif button_a.is_pressed():
        morseChr+='.'

    elif button_b.is_pressed():
        morseChr+='-'

推荐阅读