基本上,我运行的程序只是出现了这个错误'output2.append(chr(BASE +(ord(letter) - 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()
答案 0 :(得分:0)
您的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
变量。