Ceasar密码:python

时间:2016-01-07 15:35:56

标签: python encryption

解密部分无法正常工作,因为它会随机输入错误的字母,而这些字母并不是enter code here首先加密的字。例如,如果我加密'你好'加密将是' olssv'但当我解密时,它会变成“cebbe'

我认为这个问题出现在第22行' cipher2 += alphabet[(alphabet.index(A)-key)%len(cipher)]'但我不是百分百肯定。

这是我的代码。

alphabet = 'abcdefghijklmnopqrstuvwxyz'
La = len(alphabet)
message = input("Insert your message: ")
key = int(input("Insert your key: "))
cipher = ''

for A in message:
    if A in alphabet:
        cipher += alphabet[(alphabet.index(A)+key)%La]
    else:
        print ("Error")
print(cipher)

cipher2 = ''

question = input("Do you wish to decrypt? Y/N: ")

if question.lower() == 'y':
    for A in cipher:
        if A in alphabet:
            print((cipher.index(A)-key))
        cipher2 += alphabet[(alphabet.index(A)-key)%len(cipher)]
    else:
          print(cipher2)
else:
    print("Thank you")

1 个答案:

答案 0 :(得分:0)

比较你的两行:

     cipher += alphabet[(alphabet.index(A)+key)%La]
    cipher2 += alphabet[(alphabet.index(A)-key)%len(cipher)]

除了加法/减法的预期差异之外,看起来你也在改变你用于模数的东西。尝试坚持使用La

    cipher += alphabet[(alphabet.index(A)+key)%La]
    cipher2 += alphabet[(alphabet.index(A)-key)%La]