gpt4 book ai didi

Python Vigenere 元组错误

转载 作者:太空宇宙 更新时间:2023-11-03 15:31:39 26 4
gpt4 key购买 nike

我正在尝试制作维吉尼亚密码。当我尝试加密消息时,出现以下错误。

    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.

最佳答案

看来您使用的是python2.x,您应该使用raw_input而不是input

如果您的输入字符串中有空格或其他标点符号,您的代码将会崩溃,因此我建议您先确保 keyList[keyIncrement] 位于 baseAlphabet 中你使用 index 方法,如果它不在这个元组中,你会得到这个错误:

ValueError: tuple.index(x): x not in tuple

例如

if keyList[keyIncrement] in keyList:
cipherCharIndexValue = baseAlphabet.index(keyList[keyIncrement]) + baseAlphabet.index(plainTextChar)

或者您可以使用 try/catch 捕获异常以调试代码。

希望这有帮助。

关于Python Vigenere 元组错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42858038/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com