1

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)
Gabby Freeland
  • 1,527
  • 2
  • 12
  • 10

2 Answers2

2

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.")
cdlane
  • 40,441
  • 5
  • 32
  • 81
  • for the `first` method, if `word` is append then there should be 2 inputs after it so the I think it's best to use a list instead of a string; i.e. since you don't know how many words will be inputted – Gabby Freeland Sep 11 '16 at 09:06
0

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.

Alvaro Silvino
  • 9,441
  • 12
  • 52
  • 80
  • 1
    Note that ``str(s) == "quit"`` and ``str(s) is "quit"`` are fundamentally different comparisons. See http://stackoverflow.com/questions/1504717/why-does-comparing-strings-in-python-using-either-or-is-sometimes-produce – jakevdp Sep 11 '16 at 04:56
  • OK, but why am I getting an error when the user enters something else like "delfile oirgorhgoe" (which will ultimately delete file called oirgorhgoe) and the length of the list a (after s is split) with "delfile oirgorhgoe" in it is checked? – Gabby Freeland Sep 11 '16 at 04:56
  • @GabbyFreeland just tested your code and I think the first function is the issue here. – Alvaro Silvino Sep 11 '16 at 05:08
  • @GabbyFreeland can you please post the error message here ? – Alvaro Silvino Sep 11 '16 at 05:11
  • I've just posted the first function. The error was `Traceback (most recent call last): File "E:\COMPSCI 340\CS340 A2\TinyDOS.py", line 10, in class TinyDOS(): File "E:\COMPSCI 340\CS340 A2\TinyDOS.py", line 74, in TinyDOS if (len(a) is 2): first(a) File "E:\COMPSCI 340\CS340 A2\TinyDOS.py", line 43, in first word = a[0] IndexError: list index out of range` – Gabby Freeland Sep 11 '16 at 05:12
  • Even though the strings are compared incorrectly, how does that address the error? – OneCricketeer Sep 11 '16 at 05:27
  • ok, I'm still getting an error for the `word = a[0]` part in the first function though – Gabby Freeland Sep 11 '16 at 05:36
  • @GabbyFreeland have you changed the function signature? Pls tell me the outcome of print(a) – Alvaro Silvino Sep 11 '16 at 05:49
  • That part it working now, it's just saying none of the other methods I've defined are actually defined, even though they are... – Gabby Freeland Sep 12 '16 at 04:08
  • if I enter `format irughwie` then `a` will print as `['format', 'irughwie']`, then I'll get an error when the format method is called `Traceback (most recent call last): File "E:\COMPSCI 340\CS340 A2\TinyDOS.py", line 10, in class TinyDOS(): File "E:\COMPSCI 340\CS340 A2\TinyDOS.py", line 72, in TinyDOS if (len(a) is 2): first(a) File "E:\COMPSCI 340\CS340 A2\TinyDOS.py", line 48, in first form(a[1]) NameError: name 'form' is not defined` – Gabby Freeland Sep 12 '16 at 04:12