为什么这个代码在没有任何输入的情况下在启动时显示“A”?

2024-10-03 17:24:29 发布

您现在位置:Python中文网/ 问答频道 /正文

这是一个莫尔斯电码翻译为微比特,但它显示'一'开始

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”


Tags: andfromimporttruemessagemorse电码if
1条回答
网友
1楼 · 发布于 2024-10-03 17:24:29

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

首先,当您同时按A和B时,.-将被添加到消息中。要避免这种情况,请使用else if,并首先移动A和B大小写(因为这应该比A或B的优先级更高)。在

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

此外,根据microbit文档,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+='-'

相关问题 更多 >