我正在尝试通过从文件中读取所述文本并通过 2 个关键字加密来重新创建凯撒密码



基本上,我的程序在运行时出现此错误'output2.append(chr(base (ord(ord) - base newkey2 [pos])%26))indexError:列表索引以外的范围'
这是我的代码:

BASE = ord('A')
choice = input("Would you like to encrypt?")
key = input("Please enter a keyword to encrypt by: ").upper()
key2 = input("Please enter a keyword to encrypt by: ").upper()
#keyword to upper case
key = [ord(letter)- BASE + 1 for letter in key]
key2 = [ord(letter)- BASE + 1 for letter in key2]
count = 0 #This sets the count to 0
file = open("Test.txt","r")
while True:
    MSG = ''.join(chr for chr in file)
    if not chr in file: break 
newKey = (key*len(MSG))[:len(MSG)]
newKey2 = (key2*len(MSG))[:len(MSG)]     
output = []
output2 = []
pos = 0 
for letter in MSG:
    output.append(chr(BASE + (ord(letter)- BASE + newKey[pos]) % 26))
    pos += 1
print(output)
for letter in output:
    output2.append(chr(BASE + (ord(letter)- BASE + newKey2[pos]) % 26))
    pos += 1
print(output2)
print("Your encrypted message is:", ''.join(output2))        
file.close()

您的pos不会自动重置为0,这就是为什么您会遇到错误的原因。循环for letter in MSG:之后,您的pos变量为len(MSG)。然后,您正在尝试在下一个循环中访问该索引,并且您仍在增加pos。我的意思是您无法访问newkwy2[0], newkey2[1], newkey2[2], ...,而是newkwy2[len(MSG)], newkey2[len(MSG) + 1], newkey2[len(MSG) + 2], ...

避免此错误,您可以将变量重置为零之间的变量,也可以尝试这样的东西:

for index, letter in enumerate(output):
    output2.append(chr(BASE + (ord(letter)- BASE + newKey2[index]) % 26))

这样,您甚至不需要使用pos变量。

最新更新