凯撒密码循环

时间:2016-02-10 14:03:23

标签: python function

我想知道这个代码的合适循环,在它到达Z之后将它带回A,我是python的新手,这对我有很大帮助,谢谢。

reset = "yes"

def encrypt():
    answer = ""
    for letter in message:
        new=ord(letter)+ offset
        answer=answer+chr(new)
    print(answer)



def decrypt():
    answer = ""
    for letter in message:
        new=ord(letter)- offset
        answer=answer+chr(new)
    print(answer)

while reset == "yes":   
    message= input("Type in a message.")
    offset= int(input("How many do you want offset the letters by?"))
    reset = "yes"
    while offset > 26:
            offset= int(input("How many do you want offset the letters by?(0-26)"))

    eord=input("Type E for encrypt, or D for decrypt")
    if eord == "e":
        encrypt()
    elif eord == "d":
        decrypt()
    else:
        eord=input("Type E for encrypt, or D for decrypt")

    reset= input("do you want to do another?")

1 个答案:

答案 0 :(得分:0)

正如我在评论中提到的,你要求'E'或'D',但要检查'e'或'd'。在你的最后一行,你应该告诉他们输入'是'(而不是'是'或'Y')。您还需要将消息和偏移量变量传递给encypt和decrypt函数。

你提到它应该从Z回收到A(而不是在班次中使用非字母字符)。为此,您希望使用ord语句测试if值,例如this example

for letter in message:

    # ..removed some code..

    # This part in particular is what you want (for both A and a)
    elif ord(letter) == 122:   # 'z' has ord value of 122
        new = 'a'
        # and so on ...

以下是您的代码的编辑版本。它所需要的只是ordencrypt函数定义中上面提到的decrypt检查:

reset = "yes"

def encrypt(message, offset):
    answer = ""
    for letter in message:
        new=ord(letter)+ offset
        answer=answer+chr(new)
    print(answer)

def decrypt(message, offset):
    answer = ""
    for letter in message:
        new=ord(letter)- offset
        answer=answer+chr(new)
    print(answer)

while reset == "yes":   
    message= input("Type in a message.")
    offset= int(input("How many do you want offset the letters by?"))
    while offset > 26:
            offset= int(input("How many do you want offset the letters by?(0-26)"))

    eord=input("Type E for encrypt, or D for decrypt")
    while eord != 'E' or eord != 'D':
        if eord == "E":
            encrypt(message, offset)
        elif eord == "D":
            decrypt(message, offset)

    reset= input("do you want to do another (type 'yes')?")