我的caesar密码不输出任何加密的消息

时间:2015-11-12 20:00:56

标签: python encryption caesar-cipher

#Caesar Cipher Muntanga
FinalMessage=""
Mode=""
MessageNumber=""
while Mode!="encrypt" and Mode!="decrypt":
     Mode = input("Do you wish to encrypt or decrypt a message?")
     Mode = Mode.lower()

Message = input("Please enter the message you wish to encrypt:")
Message = Message.upper()

Key = input("Please enter your key:")
Key = int(Key)

if Key < 1:
     print("This program does not encrypt backwards. Please restart and enter a key between 1-25")
     raise SystemExit

elif Key > 25:
    print("You are looping round the alphabet. Please restar the program and enter a key between 1-25")
    raise SystemExit



if Mode == "encrypt":
     for i in range(0, len(Message)):
          if MessageNumber.isalpha():
               if MessageNumber.isupper():
                   MessageNumber = ord(Message[i])
                   MessageNumber = MessageNumber + Key
                   if MessageNumber > 90:
                       MessageNumber = MessageNumber - 26
                   FinalMessage = FinalMessage + chr(MessageNumber)
               elif MessageNumber.islower():
                    MessageNumber = ord(Message[i])
                    MessageNumber = MessageNumber + Key
                    if MessageNumber > 122:
                       MessageNumber = MessageNumber - 26
                    FinalMessage = FinalMessage + chr(MessageNumber)

print("Your encrypted message is:")
print(FinalMessage)
raise SystemExit

我的密码输出空白信息(检查图像) Image of failed test

2 个答案:

答案 0 :(得分:1)

您在使用MessageNumber之前有任何有意义的价值。您在脚本开头用空字符串初始化MessageNumber,但由于必须为输入字符串的每个字符设置此变量,因此您不需要对其进行初始化&#34;全局&# 34 ;.

删除初始化后,您会很快看到一条有意义的错误,指出行MessageNumber中的if MessageNumber.isalpha():为NoneType。

此外,您可以通过将这些调用更高一级来删除一些行:

if Mode == "encrypt":
     for i in range(0, len(Message)):
          MessageChar = Message[i]
          MessageNumber = ord(MessageChar)
          if MessageChar.isalpha():
               MessageNumber = MessageNumber + Key
               if MessageChar.isupper():
                   if MessageNumber > 90:
                       MessageNumber = MessageNumber - 26
               elif MessageChar.islower():
                    if MessageNumber > 122:
                       MessageNumber = MessageNumber - 26
               FinalMessage = FinalMessage + chr(MessageNumber)

答案 1 :(得分:1)

因为其他人指出了你的问题,我会告诉你一个更简单的方法来做ceasar密码转换

from string import ascii_lowercase as lc,ascii_uppercase as uc,maketrans as trans

def encode(m,rotation_amount):
    alphabet = lc+uc
    rotated_alphabet = (lc[rotation_amount:]+lc[:rotation_amount]
                       +uc[rotation_amount:]+uc[:rotation_amount])
    return m.translate(trans(alphabet,rotated_alphabet))


print encode("how are YoU")