python - 为什么此代码在没有任何输入的情况下在启动时显示“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”
解决方案
您当前的逻辑有两个问题:
首先,每当您同时按 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+='-'
推荐阅读
- visual-studio-code - 在 Windows 上的 vs 代码上打开表情符号选择器的快捷键是什么?
- python - 在 windows 中从 python 脚本打开一个文本文件
- javascript - 自定义数组类不适用于 jsdoc
- html - Powershell - 发送包含数组的电子邮件,需要将每个项目放在新行上
- python - 如何在 Python 中测试 Bobby Tables SQL 注入?
- reactjs - useEffect 被调用两次 React JS
- javascript - 服务工作者不删除旧缓存
- java - 如何从 Spring Webflux FilePart DataBuffer 中逐行读取
- php - 返回两种类型之一的对象
- python - Pandas to_datetime 格式什么都不做 - python