2017-05-10 141 views
0

我的Python函數有錯誤。代碼如下所示。Python TypeError:列表索引必須是整數或切片,而不是str

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================
vigenere()
message: flee
Traceback (most recent call last):
File "", line 1, in
vigenere()
File "/Users/gg-mac/Documents/ProjectM.py", line 75, in vigenere
encrypting = chr(ord(med) + ord(keyl[med]))
TypeError: list indices must be integers or slices, not str

您能否幫助我,告訴我我的錯誤?

回答

0

列表索引必須是整數。以下內容應該解決您的問題。

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) 
+0

非常感謝。這解決了我的問題。 –

+0

現在擔心。如果它有幫助,請接受它作爲你的答案。 – Allen

相關問題