摩尔斯电码程序我只需要一点整洁的指导

时间:2017-11-15 14:41:25

标签: python python-3.x python-2.7

这是我输入摩尔斯电码的代码

 public class MyAPIController : System.Web.Http.ApiController

当程序重新启动时,它在Morse代码所在的同一行开始,我不知道在哪里放错误打印,所以如果有人输入一个数字,则表示重试或重新启动前出错

2 个答案:

答案 0 :(得分:1)

你应该重构并使用函数来获取用户的输入,然后将消息翻译成莫尔斯:

def get_message():
    while True:
        message = input("please enter your word or words: ")
        message = message.lower()
        for c in message:
            if c not in alphabet:
                print("please enter a message using the correct alphabet")
                break
        else:
            return message

def translate(message):
    code = []
    for c in message:
        code.append(morse[c])
    return ' '.join(code)

alphabet = 'abcdefghijklmnopqrtsuvwxyz '
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":"--.."}

print(translate(get_message()))

答案 1 :(得分:0)

在这里: -

def main():
    morse_code = {"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":"--.."}

    phrase = input("please enter your word or words: ")

    if any(char.isdigit() for char in phrase):
        print("try again")
    else:
        print("your word or sentence translated to morse code is : ", end = '')
        code = ' '.join(morse_code[key] for key in phrase)
        print(code)


def retry():
    main()
retry()