为什么此代码在启动时没有任何输入就显示“ A”?

YEp*_*p d 3 python micropython bbc-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()
Run Code Online (Sandbox Code Playgroud)

我希望它可以将按下的按钮转换为一条消息,但仅显示“ A”

Fit*_*tzi 6

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

首先,每当您同时按A和B时,.-都会被添加到您的信息中。为避免这种情况,请使用an else if并先移动A和B大小写(因为它的优先级应高于A或B)。

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

此外,is_pressed是根据微比特文档的功能。

结果代码如下所示:

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+='-'
Run Code Online (Sandbox Code Playgroud)