当我运行这个程序(它应该对Caesar密码进行编码和解码)并选择decode选项时,我得到的错误是字符串索引超出了范围。有人能告诉我怎么解决这个问题,告诉我为什么会这样吗?我输入的要解码的文本是ibmmp,键是1。谢谢。你知道吗
alphabet = "abcdefghijklmnopqrstuvwxyz"
encdec = input("Would you like to encode or decode a message? ")
if encdec == "decode":
keyyn = input("Do you know the key to your encoded text? (Y/N) ")
if keyyn == "Y":
plaintext = input("Please type in your text ")
text = plaintext
key = int(input("What is the key? "))
for i in range(len(plaintext)):
letter = plaintext[i]
alphletter = alphabet.find(letter)
alphletter = alphletter - key
if alphletter < 0 or alphletter == 0:
alphletter = alphletter + 26
letter = alphabet[alphletter]
plaintext = plaintext + letter
else:
letter = alphabet[alphletter]
plaintext = plaintext + letter
print(plaintext.strip(text))
else:
print("This program is unable to decode a message without the key")
问题:
ibmmp
和1的键i
起作用,b
给您一个错误。原因如下:可以使用模运算符
%
修复溢出/下溢:您也可以使用
if alphletter < 0:
-这将不会处理多次环绕的键(例如210
)或负键-22
一些优化
输出:
相关问题 更多 >
编程相关推荐