【发布时间】:2017-03-17 12:49:32
【问题描述】:
我正在尝试制作 Vigenere 密码。当我尝试加密消息时,出现以下错误。
cipherCharIndexValue = baseAlphabet.index(keyList[keyIncrement]) + baseAlphabet.index(plainTextChar)
ValueError: tuple.index(x): x not in tuple
我不确定是什么问题导致了错误,有什么帮助吗?
baseAlphabet = ('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o',
'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z')
plainText = input("Please enter the plain text")
key = input("Please enter the key word")
keyList = []
keyLength = 0
while keyLength < len(plainText):
#Adds the users entered key into a list character by character.
#Also makes the key the same length as plainText
for char in key:
if keyLength < len(plainText):
keyList.append(str(char))
keyLength = keyLength + 1
#The variable each processed letter is appended to
completeCipherText = []
#This is the value used to temporaily store the ciphertext character during the iteration
cipherCharIndexValue = 0
keyIncrement = 0
#iterates through the plain text
for plainTextChar in plainText:
#Adds the base alphabets index value of the key and the plain text char
cipherCharIndexValue = baseAlphabet.index(keyList[keyIncrement]) + baseAlphabet.index(plainTextChar)
while cipherCharIndexValue > 25:
#makes the addition value under 26 as to not go out of range of base alphabet tuple
cipherCharIndexValue = cipherCharIndexValue - 26
#appends the ciphertext character to the completeCipherText variable.
#The character is the index of the key + index of the plainTextChar from baseAlphabet
completeCipherText.append(baseAlphabet[cipherCharIndexValue])
#Moves onto the next key
keyIncrement = keyIncrement + 1
print ('').join(completeCipherText)#Makes the result a strings for printing to the console.
【问题讨论】:
-
我尝试运行您的代码并在第 2 行得到一个 IndentationError。在取消缩进包括第一个 while 循环的所有内容后,我在第 28 行得到一个 IndentationError。在取消缩进该行之后一个空格,我得到了
NameError: name 'baseAlphabet' is not defined。请发一个minimal reproducible example 来证明你的问题。 -
keyList[keyIncrement]或plainTextChar不在baseAlphabet中。您需要进行一些故障排除才能确定究竟是哪个值失败了。 -
感谢您编辑代码。它现在为我运行。当我使用 Python 2 执行它,并为第一个提示输入
"foo"并为第二个提示输入"bar"时,它运行时不会崩溃并输出gof。请描述您输入的哪些输入导致程序崩溃。 -
考虑如果
plainText(或keyList)包含一个不在baseAlphabet中的字符会发生什么。