谁能帮我这是一个摩尔斯电码程序,我希望用户输入t或m;t;文本和m摩尔斯电码每次我运行它时,无论我是否输入,它总是说输入摩尔斯电码翻译,而不是输入文本翻译,我感谢任何帮助!
while True:
print("")
Input = input("My input is: ")
message=input("Enter morse code to translate: ")
encodedMessage = ""
if Input.startswith ("m"):
for word in message.split(" "):
for char in word.split():
if char in morse:
encodedMessage+=morse[char] + " "
print("Your translation to text is: ",encodedMessage)
else:
print("Value for %r not found as morse."%char)
if Input.startswith ("t"):
print("Enter text to translate: ")
decodedMessage = ""
for word in hello.split():
if char in morseCode:
decodedMessage+=morseCode[char] + " "
print("Your translation to morse is: ",decodedMessage)
else:
print("Value for %r not found as a character."%char)
发布于 2015-04-28 10:35:30
对于以t开头的输入,您的第二个if语句缩进太多,以至于只有当输入以"m“开头时,它才会执行(因此会失败)。接下来,您让输入在if语句之外请求提供摩尔斯电码(所以它总是显示出来,而不是在您验证了您要查找的代码之后)。我将其更改为更接近我认为您想要的内容:
while True:
print("")
Input = input("My input is: ")
if Input.startswith ("m"):
message=input("Enter morse code to translate: ")
encodedMessage = ""
for word in message.split(" "):
for char in word.split():
if char in morse:
encodedMessage+=morse[char] + " "
else:
print("Value for %r not found as morse."%char)
print("Your translation to text is: ",encodedMessage)
elif Input.startswith ("t"):
hello = input("Enter text to translate: ")
decodedMessage = ""
for word in hello.split():
for char in word:
if char in morseCode:
decodedMessage+=morseCode[char] + " "
else:
print("Value for %r not found as a character."%char)
print("Your translation to morse is: ",decodedMessage)
我还将最后的print行移到了for循环之外,因为您可能不想缓慢地打印出每个字符的编码/解码消息,而只是打印出最终结果。我还添加了一个for循环,用于查看文本以遍历单词中的每个字符。
发布于 2015-04-28 10:39:26
使用==
而不是startswith
进行比较。
变化
if Input.startswith ("m"):
至
if Input == "m":
https://stackoverflow.com/questions/29909287
复制相似问题