gpt4 book ai didi

python - 为什么此代码在没有任何输入的情况下启动时显示 'A'?

转载 作者:太空宇宙 更新时间:2023-11-03 13:25:35 24 4
gpt4 key购买 nike

这是一个用于 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”

最佳答案

你现在的逻辑有两个问题:

首先,当您同时按下 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+='-'

关于python - 为什么此代码在没有任何输入的情况下启动时显示 'A'?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56767449/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com