简体   繁体   中英

“list index out of range” exception (Python3)

I keep getting a list index out of range exception when I check the length of the list a. The error pops up for either the if or elif part of the second if statement, depending on what the user inputs. I know that when the user input is split the list is created correctly because I print it out... So I'm a little lost about why I'm getting that error.

if __name__ == '__main__':
            for line in sys.stdin:
                    s = line.strip()
                    if not s: break
                    if (str(s) is "quit") == True: quit()
                    elif (str(s) is "quit") == False:
                            a = s.split()
                            print(a)
                            if (len(a) == 2) == True: first(a)
                            elif (len(a) == 3) == True: first(a)
                            else: print("Invalid Input. Please Re-enter.")

The first method is: (The methods it calls in the if statement just print things out at the moment)

def first(self, a = list()):
            word = a[0]

            if word is ls:
                    ls(a[1])           
            elif word is format:
                    form(a[1])        # EDIT: was format
            elif word is reconnect:
                    reconnect(a[1])
            elif word is mkfile:
                    mkfile(a[1])
            elif word is mkdir:
                    mkdir(a[1])
            elif word is append:
                    append(a[1], a[2])                               
            elif word is delfile:
                    delfile(a[1])
            elif word is deldir:
                    deldir(a[1])
            else:
                    print("Invalid Prompt. Please Re-enter.")

Other methods:

    def reconnect(one = ""):
            print("Reconnect")

    def ls(one = ""):
            print("list")

    def mkfile(one = ""):
            print("make file")

    def mkdir(one = ""):
            print("make drive")

    def append(one = "", two = ""):
            print("append")

    def form(one = ""):
            print("format")

    def delfile(one = ""):
            print("delete file")

    def deldir(one = ""):
            print("delete directory")

    def quit():
            print("quit")
            sys.exit(0)

The problem seems to be the definition of first() . You invoke it as a function:

if (len(a) == 2) == True: first(a)
elif (len(a) == 3) == True: first(a)

But you define it as a method:

def first(self, a = list()):

The array of command and argument gets put into self and a is always an empty list which you attempt to index and fail. Also, you shouldn't use a mutable type like list() as a default value unless you're certain what you are doing. I suggest simply:

def first(a):

As far as your __main__ code goes, simplify:

if __name__ == '__main__':

    for line in sys.stdin:
        string = line.strip()

        if not string:
            break

        if string == "quit":
            quit()

        tokens = string.split()

        length = len(tokens)

        if 2 <= length <= 3:
            first(tokens)
        else:
            print("Invalid Input. Please Re-enter.")

Real issue:

To solve your error you have to remove the self parameter of the first function

def first(a=list())

Basically the self is only used for object orientation creating methods. Function like yours can't use self otherwise you will passing the first parameter to self not to a which you want to.

My second issue I can point out is that, You are trying to compare using is between a string and a function .

 def first(a = list()):
        word = a[0]

        if word is "ls":
                ls(a[1])           
        elif word is "format":
                format(a[1])
        elif word is "reconnect":
                reconnect(a[1])
        elif word is "mkfile":
                mkfile(a[1])
        elif word is "mkdir":
                mkdir(a[1])
        elif word is "append":
                append(a[1], a[2])                               
        elif word is "delfile":
                delfile(a[1])
        elif word is "deldir":
                deldir(a[1])
        else:
                print("Invalid Prompt. Please Re-enter.")

Extra

The is function on built in operations in Python. is compare the equity of the objects.

But this expression:

if (str(s) is "quit") == True:

Can be simpler like:

if str(s) == "quit":

Or:

if str(s) is "quit":

The == True is meaningless either == False you can use not more pythonicly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM