任何人都可以帮我解决它的莫尔斯代码程序,我希望用户输入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)
答案 0 :(得分:2)
你的输入的第二个if语句以t方式过于缩进开始,只有当输入以" m"开头时才会执行。 (因此失败了)。接下来,您在if语句之外输入了要求morse代码的输入(所以它总是显示出来,而不是在您验证了您要查找的内容之后)。我已将其更改为更接近我认为您想要的内容:
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)
我还将你的最终打印行移到for循环之外,因为你可能不想在每个字符上慢慢打印出编码/解码的消息,而只是结果。我还添加了一个for循环,以便您查看文本以循环显示单词中的每个字符。
答案 1 :(得分:2)
使用==
进行比较而不是startswith
。
更改
if Input.startswith ("m"):
到
if Input == "m":