为什么索引在这个程序中超出界限?

时间:2015-09-12 18:06:10

标签: python list python-2.7 indexoutofboundsexception

出于某种原因,我在运行它并输入我的26个字母键时在python 2.7中出现错误。它说列表索引超出范围。任何帮助将不胜感激。谢谢! (而且我知道我可以使用encrypter的循环

#-------------------------#
#     Code Translator     #
#-------------------------#

message = ''
messagearray = []
user = ''
encrypted = []
decrypted = []
keystring = ''
alphabet = ['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']
dataset = []
keyarray = []

def encrypter():
    keystring = raw_input("Please paste key: ")
    message = raw_input("Message to Encrypt: ")

    for char in message:
        if char == alphabet[0]:
            messagearray.append(keyarray[0])
        elif char == alphabet[1]:
            messagearray.append(keyarray[1])
        elif char == alphabet[2]:
            messagearray.append(keyarray[2])
        elif char == alphabet[3]:
            messagearray.append(keyarray[3])
        elif char == alphabet[4]:
            messagearray.append(keyarray[4])
        elif char == alphabet[5]:
            messagearray.append(keyarray[5])
        elif char == alphabet[6]:
            messagearray.append(keyarray[6])
        elif char == alphabet[7]:
            messagearray.append(keyarray[7])
        elif char == alphabet[8]:
            messagearray.append(keyarray[8])
        elif char == alphabet[9]:
            messagearray.append(keyarray[9])
        elif char == alphabet[10]:
            messagearray.append(keyarray[10])
        elif char == alphabet[11]:
            messagearray.append(keyarray[11])
        elif char == alphabet[12]:
            messagearray.append(keyarray[12])
        elif char == alphabet[13]:
            messagearray.append(keyarray[13])
        elif char == alphabet[14]:
            messagearray.append(keyarray[14])
        elif char == alphabet[15]:
            messagearray.append(keyarray[15])
        elif char == alphabet[16]:
            messagearray.append(keyarray[16])
        elif char == alphabet[17]:
            messagearray.append(keyarray[17])
        elif char == alphabet[18]:
            messagearray.append(keyarray[18])
        elif char == alphabet[19]:
            messagearray.append(keyarray[19])
        elif char == alphabet[20]:
            messagearray.append(keyarray[20])
        elif char == alphabet[21]:
            messagearray.append(keyarray[21])
        elif char == alphabet[22]:
            messagearray.append(keyarray[22])
        elif char == alphabet[23]:
            messagearray.append(keyarray[23])
        elif char == alphabet[24]:
            messagearray.append(keyarray[24])
        elif char == alphabet[25]:
            messagearray.append(keyarray[25])

    print ''.join(messagearray) 




def decrypter():
    keystring = raw_input("Please paste key: ")
    message = raw_input("Message to Decrypt: ")





def outputM():
    print decrypted

def userChoice():
    user = raw_input("Encrypt or Decrypt?")
    if user.upper() == "ENCRYPT":
        encrypter()
    elif user.upper() == "DECRYPT":
        decrypter()
    else:
        print "Please enter a valid command."
        userChoice()

for char in keystring:
    keyarray.append(char)

userChoice()

这是我得到的全部追溯:

Traceback (most recent call last):
  File "translate.py", line 102, in <module>
    userChoice()
  File "translate.py", line 92, in userChoice
    encrypter()
  File "translate.py", line 43, in encrypter
    messagearray.append(keyarray[11])
IndexError: list index out of range

2 个答案:

答案 0 :(得分:2)

问题在于:

for char in keystring:
    keyarray.append(char)

keystring为空,因此keyarray也将保持为空。为了不使用IndexError,你需要一个比字母更长的键串(因为基本上你只是用字符代替)

答案 1 :(得分:1)

问题在于:

def decrypter():
    keystring = raw_input("Please paste key: ")
    message = raw_input("Message to Decrypt: ")

您要将值分配给本地变量,因此全局变量仍为空。如果要修改全局变量,则必须说明:

def decrypter():
    global keystring, message
    keystring = raw_input("Please paste key: ")
    message = raw_input("Message to Decrypt: ")

encrypter也是如此。

另外,在进行一些输入之前,您无法创建keyarray

代码还有许多其他问题。你不可能认为进行所有手动索引是最好的方法。如果你想支持128个字符的字母怎么办?

使用循环:

for char in message:
    for i, c in enumerate(alphabet):
        if char == c:
            messagearray.append(keyarray[i])

(而不是所有那些重复的行)。

此外,字符串已经提供了一种方法来完成你想要做的事情。它被称为translate

你可以这样做:

import string

table = str.maketrans(string.ascii_lowercase, keystring)

然后使用:

decrypted_text = some_encrypted_text.translate(table)

示例运行:

In [1]: import string
   ...: alphabet = string.ascii_lowercase
   ...: table = str.maketrans(alphabet, alphabet[3:]+alphabet[:3])
   ...: 

In [2]: 'hello'.translate(table)
Out[2]: 'khoor'

以上是python3 +。在python2.7中,您必须使用string.maketrans而不是str.maketrans。所以你必须这样做:

In [1]: import string
   ...: alphabet = string.ascii_lowercase
   ...: table = string.maketrans(alphabet, alphabet[3:]+alphabet[:3])
   ...: 

In [2]: 'hello'.translate(table)
Out[2]: 'khoor'