编码/解码Caesar cipher Python 3 ASCII

2024-10-01 15:29:55 发布

您现在位置:Python中文网/ 问答频道 /正文

我是通过约翰·泽尔写的计算机科学导论来学习编码的。我坚持练习5.8。我需要以某种方式修改这个解决方案,其中“z”后面的下一个字符是“a”,以便使它循环。任何帮助都会很好:)

def main():
    print("This program can encode and decode Caesar Ciphers") #e.g. if key value is 2 --> word shifted 2 up e.g. a would be c
    #input from user
    inputText = input("Please enter a string of plaintext:").lower()
    inputValue = eval(input("Please enter the value of the key:"))
    inputEorD = input("Please enter e (to encrypt) or d (to decrypt) ")
    #initate empty list
    codedMessage = ""

    #for character in the string
    if inputEorD == "e":
        for ch in inputText:
            codedMessage += chr(ord(ch) + inputValue) #encode hence plus
    elif inputEorD =="d":
            codedMessage += chr(ord(ch) - inputValue) #decode hence minus
    else:
        print("You did not enter E/D! Try again!!")
    print("The text inputed:", inputText,  ".Is:", inputEorD, ".By the key of",inputValue, ".To make the message", codedMessage)

main()

Tags: ofthekeyinputmainchencodeprint
1条回答
网友
1楼 · 发布于 2024-10-01 15:29:55

因为您处理的是.lower()-大小写字母,所以可以知道它们的ASCII范围是[97-122]。在

使移位循环的一个好方法是用范围[0-25]表示每个字母,这是通过ord(ch) - 97来完成的,然后添加键,然后将结果与26模化,使其成为(ord(ch) - 97 + key)%26,我们将得到范围为[0-25]的结果,添加97将得到它的ASCII码:

def main():
    print("This program can encode and decode Caesar Ciphers")
    inputText = input("Please enter a string of plaintext:").lower()
    inputValue = int(input("Please enter the value of the key:")) # use int(), don't eval unless you read more about it
    inputEorD = input("Please enter e (to encrypt) or d (to decrypt) ")
    codedMessage = ""

    if inputEorD == "e":
        for ch in inputText:
            codedMessage += chr((ord(ch) - 97 + inputValue)%26 + 97)
    elif inputEorD =="d":
            codedMessage += chr((ord(ch) - 97 - inputValue)%26 + 97)
    else:
        print("You did not enter E/D! Try again!!")
    print("The text inputed:", inputText,  ".Is:", inputEorD, ".By the key of",inputValue, ".To make the message", codedMessage)

main()

相关问题 更多 >

    热门问题