我的程序不断循环,我无法弄清楚原因

时间:2017-05-18 17:26:01

标签: python-3.x

我的程序不断循环,我想弄清楚为什么在我进一步进入项目之前它自己。程序的目的是从字母表中创建用于解码/编码消息的密钥。

import random 
    def main():
        userselection = "0"
        print("This program allows you to create keys, econde plaintext, and decode ciphertext.")
        while userselection != "4":
            print("What would you like to do?")

        userselection = input("1.create a key 2.encode a message 3.decode a message 4.quit > ")
        if userselection == "1":
        #selection 1 stuffs goes here
            alphabet = "abcdefghijklmnopqrstuvwxyz"
            key = ""
            letter = random.choice(alphabet)

        elif userselection == "2":
        #selection 2 stuffs 
            plaintext = plaintext.lower()
            ciphertext = ""
            for i in range(len(plaintext)):
                alphabetposition = alphabet.find(plaintext[i])

            if alphabetposition >= 0:
                ciphertext = ciphertext + key[alphabetposition]
            else:
                ciphertext = cipertext + plaintext[i]

        elif userselection == "3":
        #selection 3 stuffs
            print()

        elif userselection != "4":
            print("invalid selection")






    if __name__ == "__main__":
        main()

2 个答案:

答案 0 :(得分:0)

我认为您需要在while循环中接受用户输入。试试这个: -

import random 
    def main():
        userselection = "0"
        print("This program allows you to create keys, econde plaintext, and decode ciphertext.")
        while userselection != "4":
            print("What would you like to do?")
            userselection = input("1.create a key 2.encode a message 3.decode a message 4.quit > ")
        if userselection == "1":
        #selection 1 stuffs goes here
            alphabet = "abcdefghijklmnopqrstuvwxyz"
            key = ""
            letter = random.choice(alphabet)

        elif userselection == "2":
        #selection 2 stuffs 
            plaintext = plaintext.lower()
            ciphertext = ""
            for i in range(len(plaintext)):
                alphabetposition = alphabet.find(plaintext[i])

            if alphabetposition >= 0:
                ciphertext = ciphertext + key[alphabetposition]
            else:
                ciphertext = cipertext + plaintext[i]

        elif userselection == "3":
        #selection 3 stuffs
            print()

        elif userselection != "4":
            print("invalid selection")

    if __name__ == "__main__":
        main()

答案 1 :(得分:0)

循环处于错误位置。它在你设置userselection =" 0"时循环之后,在用户输入之前检查 用户选择!=" 4":     打印("你想做什么?")

我建议您注意这一行并重新运行。