首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Python循环程序

Python循环程序
EN

Stack Overflow用户
提问于 2015-04-28 10:31:15
回答 2查看 61关注 0票数 1

谁能帮我这是一个摩尔斯电码程序,我希望用户输入t或m;t;文本和m摩尔斯电码每次我运行它时,无论我是否输入,它总是说输入摩尔斯电码翻译,而不是输入文本翻译,我感谢任何帮助!

代码语言:javascript
运行
复制
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)
EN

回答 2

Stack Overflow用户

发布于 2015-04-28 10:35:30

对于以t开头的输入,您的第二个if语句缩进太多,以至于只有当输入以"m“开头时,它才会执行(因此会失败)。接下来,您让输入在if语句之外请求提供摩尔斯电码(所以它总是显示出来,而不是在您验证了您要查找的代码之后)。我将其更改为更接近我认为您想要的内容:

代码语言:javascript
运行
复制
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循环,用于查看文本以遍历单词中的每个字符。

票数 2
EN

Stack Overflow用户

发布于 2015-04-28 10:39:26

使用==而不是startswith进行比较。

变化

代码语言:javascript
运行
复制
if Input.startswith ("m"):

代码语言:javascript
运行
复制
if Input == "m":
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/29909287

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档