2015-12-13 5 views
-1

Я пишу шифр vigenere для личного проекта, и я сталкиваюсь с ошибкой индекса. это говорит IndexError: list index out of range. Линия, вызывающая это IndexValue = Alphabet.index(keyList[keyIncrement]) + Alphabet.index(plainTextChar).IndexError: индекс индекса вне диапазона в python

Вот весь код:

playing = True 
string = "" 
Alphabet = ('z','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') 

while playing == True: 
    string = "" 
    eord = input('Type "d" to "decrypt" and "e" to "encrypt": ') 

    if eord == 'e': 
     texte = input ("Type your word to encrypt: ") 
     key1 = int(input("Choose a key between 1-26: ")) 
     for letter in texte: 
      number = (ord(letter)) + (key1) 
      letter=(chr(number)) 
      string = (str(string)) + (str(letter)) 
     print (string) 
     keyword = input ("Type 'encrypt' code further or 'decrypt' further: ") 

     if keyword == 'encrypt': 
      plainText = input("Please enter the plain text: ") 
      key = input("Please enter the key: ") 
      keyList = [] 
      keyLength = 0 
      while keyLength < len(plainText): 
       for char in key: 
        if keyLength < len(plainText): 
         keyList.append(str(char)) 
         keyLength = keyLength + 1 
         CipherText = [] 
         IndexValue = 0 
         keyIncrement = 0 
        for plainTextChar in plainText: 
         IndexValue = Alphabet.index(keyList[keyIncrement]) + Alphabet.index(plainTextChar) 
         while IndexValue > 26: 
          IndexValue = IndexValue - 26 
         CipherText.append(Alphabet[IndexValue]) 
         keyIncrement = keyIncrement + 1 
         print (''.join(CipherText)) 

      finish = input('Would you like to go again Y or N') 
      if finish == 'n' or finish == 'N': 
       retry = input ("Would you like to go again? Y or N: ") 
       if retry == 'N' or retry == 'n': 
        print ("Please exit the window") 
        import time 
        time.sleep(1) 
        import sys 
        sys.exit() 

    elif eord == 'd': 
     texd = input ("Type your word to decrypt: ") 
     key2 = int(input("Choose a key between 1-16: ")) 

     for letter in texd: 
      number = (ord(letter)) - (key2) 
      letter=(chr(number)) 
      string = (str(string)) + (str(letter)) 
     print (string) 
     keyword = input ("Type 'encrypt' code further or 'decrypt' further: ") 

     if keyword == 'decrypt': 
      plainText = input("Please enter the plain text: ") 
      key = input("Please enter the key: ") 
      keyList = [] 
      keyLength = 0 
      while keyLength < len(plainText): 
       for char in key: 
        if keyLength < len(plainText): 
         keyList.append(str(char)) 
         keyLength = keyLength - 1 
         completeCipherText = [] 
         cipherCharIndexValue = 0 
         keyIncrement = 0 
        for plainTextChar in plainText: 
         cipherCharIndexValue = Alphabet.index(keyList[keyIncrement]) + Alphabet.index(plainTextChar) 
         while cipherCharIndexValue > 26: 
          cipherCharIndexValue = cipherCharIndexValue + 26 
         completeCipherText.append(Alphabet[cipherCharIndexValue]) 
         keyIncrement = keyIncrement - 1 
         print (''.join(completeCipherText)) 

         finish = input('Would you like to go again Y or N') 
         if finish == 'n' or finish == 'N': 
          retry = input ("Would you like to go again? Y or N: ") 
          if retry == 'N' or retry == 'n': 
           print ("Please exit the window") 
           import time 
           time.sleep(1) 
           import sys 
           sys.exit() 

Секция это происходит так:

if keyword == 'encrypt': 
      plainText = input("Please enter the plain text: ") 
      key = input("Please enter the key: ") 
      keyList = [] 
      keyLength = 0 
      while keyLength < len(plainText): 
       for char in key: 
        if keyLength < len(plainText): 
         keyList.append(str(char)) 
         keyLength = keyLength + 1 
         CipherText = [] 
         IndexValue = 0 
         keyIncrement = 0 
        for plainTextChar in plainText: 
         IndexValue = Alphabet.index(keyList[keyIncrement]) + Alphabet.index(plainTextChar) 
         while IndexValue > 26: 
          IndexValue = IndexValue - 26 
         CipherText.append(Alphabet[IndexValue]) 
         keyIncrement = keyIncrement + 1 
         print (''.join(CipherText)) 

Что не так с кодом, потому что я попытался с помощью PyCharm и выделены [keyIncrement], но я не знаю, как это исправить. Спасибо за любую помощь заранее.

+0

Прочитайте сообщение об ошибке более тщательно. Вы не указали какую-либо полезную информацию, такую ​​как номер строки и т. Д. Вся необходимая информация есть. Наиболее вероятной проблемой является то, что 'keyIncrement' больше размера списка' keyList'. Попробуйте распечатать индекс и размер списка прямо перед строкой. –

+0

Я бы попробовал отладить его с помощью PyCharm и поставить точку останова на линии с ошибкой. Это должно дать вам представление о том, какое значение выходит за пределы допустимого диапазона, и помочь вам разобраться в том, что задало его значение вне диапазона. –

+0

«Traceback (последний последний звонок): Файл«/home/owain/Documents/USB 2/## Python Cipher ##. Py », строка 33, в IndexValue = Alphabet.index (keyList [keyIncrement]) + Alphabet.index (plainTextChar) IndexError: индекс индекса вне диапазона '. Это сообщение об ошибке –

ответ

0

Ваша проблема заключалась в том, что оператор if keyLength < len(plainText): блокировал for character in key от добавления каждого символа в список перед запуском остальной части кода.

while keyLength < len(plainText): 
    try: 
     char = key[num] 
    except IndexError: 
     num = 0 
     char = key[num] 
    keyList.append(str(char)) 
    keyLength += 1 
    num += 1 
    CipherText = [] 
    IndexValue = 0 
    keyIncrement = 0 
for plainTextChar in plainText: 
    IndexValue = Alphabet.index(keyList[keyIncrement]) + Alphabet.index(plainTextChar) 
    while IndexValue > 26: 
     IndexValue = IndexValue - 26 
    CipherText.append(Alphabet[IndexValue]) 
    keyIncrement = keyIncrement + 1 
    print (''.join(CipherText)) 

Пробное:

Type "d" to "decrypt" and "e" to "encrypt": e 
Type your word to encrypt: hello 
Choose a key between 1-26: 3 
khoor 
Type 'encrypt' code further or 'decrypt' further: encrypt 
Please enter the plain text: darrien 
Please enter the key: brit 
f 
fs 
fsa 
fsal 
fsalk 
fsalkw 
fsalkww 
Would you like to go again Y or N 
+0

зп SNX snxm Traceback (самый последний вызов последнего): "/ дом/Оуайн/Документы/USB 2/## Python Cipher ## ру" файла , строка 32, в IndexValue = Alphabet.index (KeyList [keyIncrement]) + Alphabet.index (plainTextChar) IndexError: индекс списка из диапазона –

+0

Он сделал что-то, но все еще есть ошибка :( –

+0

на самом деле я просто побежал через это несколько раз, что вы печатаете, это все еще 'e',' hello', '3',' encrypt', 'python',' cypher'? –