我的Python函数出错了。代码如下所示。
def vigenere():
message1 = input('message: ')
keyl = ['l', 'e', 'm', 'o', 'n']
if len(message1) > len(keyl):
keyl = [i * 5 for i in keyl]
else:
pass
for med in message1:
encrypting = chr(ord(med) + ord(keyl[med]))
print(encrypting)
encmessage = input('Is there a message you would like to decrypt?')
for mes in encmessage:
decrypting = chr(ord(med) - ord(keyl[med]))
print(decrypting)
当我尝试调用我的函数时,python shell演示了一个错误。错误如下所示。
================ RESTART:/Users/ggmac/Documents/ProjectM.py================
的V @ genere()
消息:逃离 追溯(最近的呼叫最后):
文件"",第1行,在 的V @ genere()
文件" /Users/gg-mac/Documents/ProjectM.py" ;,第75行,在vigenere中 encrypting = chr(ord(med)+ ord(keyl [med]))
TypeError:list indices必须是整数或切片,而不是str
你能帮忙告诉我我的错误吗?
答案 0 :(得分:2)
列表索引必须是整数。以下内容应该可以解决您的问题。
def vigenere():
message1 = input('message: ')
keyl = ['l', 'e', 'm', 'o', 'n']
if len(message1) > len(keyl):
keyl = [i * 5 for i in keyl]
else:
pass
for i,med in enumerate(message1):
encrypting = chr(ord(med) + ord(keyl[i]))
print(encrypting)
encmessage = input('Is there a message you would like to decrypt?')
for k, mes in enumerate(encmessage):
decrypting = chr(ord(med) - ord(keyl[k]))
print(decrypting)