Python 凯撒密码解码不工作

Python 凯撒密码解码不工作,python,encryption,Python,Encryption,我试图让凯撒密码工作,我可以得到编码,但没有使用-移位解码。我认为这可能是真的,但几乎没有成功 提前谢谢大家 def helper(message, shift): message = message.lower() secret = "" for c in message: if c in "abcdefghijklmnopqrstuvwxyz": num = ord(c) num += shift

我试图让凯撒密码工作,我可以得到编码,但没有使用-移位解码。我认为这可能是真的,但几乎没有成功

提前谢谢大家

def helper(message, shift):
    message = message.lower()

    secret = ""
    for c in message:
        if c in "abcdefghijklmnopqrstuvwxyz":
            num = ord(c)
            num += shift
            if num > ord("z"):     # wrap if necessary
                num -= 26
            elif num < ord("a"):
                num += 26
            secret = secret + chr(num)
        else:
        # don't modify any non-letters in the message; just add them as-is
            secret = secret + c
    return secret

#   Encrypts the given string using a Caesar cipher and returns the result.


def encrypt(message):
        return helper(message, x)

#   Decrypts a string that was previously encrypted using a Caesar cipher and returns the result.
def decrypt(message):
    return helper(message, x)




t=input('e or d ')
msg = input("Your message to encode? ")
x = int(input('no '))


if len (msg) > 0:
# wants to encrypt
    secret = encrypt(msg)
    print("The encoded message is:", secret)
else:
# empty message; wants to decrypt
    secret = input("Your message to decode? ")
    if len(secret) > 0:
        msg = decrypt(secret)
        print("The decoded message is:" ,msg)
def助手(消息,班次):
message=message.lower()
secret=“”
对于消息中的c:
如果“abcdefghijklmnopqrstuvxyz”中的c:
num=ord(c)
num+=移位
如果num>ord(“z”):#必要时包装
num-=26
以利夫数:
num+=26
secret=secret+chr(num)
其他:
#不要修改邮件中的任何非字母;只需按原样添加即可
秘密=秘密+c
归还秘密
#使用Caesar密码加密给定字符串并返回结果。
def加密(消息):
返回帮助程序(消息,x)
#解密以前使用Caesar密码加密的字符串并返回结果。
def解密(消息):
返回帮助程序(消息,x)
t=输入('e或d')
msg=input(“您要编码的消息?”)
x=int(输入('no'))
如果len(msg)>0:
#想要加密吗
secret=加密(msg)
打印(“编码消息为:”,机密)
其他:
#空话;想要解密
secret=输入(“您要解码的消息?”)
如果len(secret)>0:
msg=解密(秘密)
打印(“解码信息为:”,msg)

解密应该与加密方向相反

def decrypt(message):
    return helper(message, -x)
现在,您可以使用相同的密码进行解密和加密

x = 5
msg = "hello"
print("plaintext message:", msg)
print("encrypted message:", encrypt(msg))
print("decrypted message:", decrypt(encrypt(msg)))
结果:

plaintext message: hello
encrypted message: mjqqt
decrypted message: hello

我会考虑使用模算符,而不是简单地加法或减法26。