1

I'm having a problem with a try except within a while loop. I'm still relatively new to programming and this is part of my A2 Comp4 project.

def CheckValidInitials(initials):
    CheckIfTrue = False
    Count = 1
    while CheckIfTrue == False:
        while len(initials) == int(3) or len(initials) == int(4):
            listInitials = list(initials)
            print(len(initials))
            while len(listInitials) - Count >= 0:
                print(len(initials))
                print(len(listInitials) - Count)
                Count = Count + 1
                print(listInitials)
                try:
                    int(listInitials[Count])
                except IndexError and ValueError:
                    CheckIfTrue = True
                else:
                    print("One of your initials is a number, this is not valid")
                    print()
                    Count = 1
                    initials = input("Please enter valid initials: ")
                    listInitials = list(initials)

        else:
            initials = input("Please enter valid initials: ")
        return initials

I keep getting this error:

  File "D:\A2 Computing\Comp4\Prototype\Prototype Mk 3\TeacherInfo.py", line 105, in CheckValidInitials
    int(listInitials[Count])
IndexError: list index out of range

My problem with this is that I thought I excepted IndexError's in my try except. It is supposed to be throwing up this problem.

The overall code is supposed to be checking whether initials (entered in another function) contain any numbers.

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
Ben
  • 529
  • 1
  • 4
  • 8
  • `except OneException and AnotherException` isn't the right syntax for a catch block that handles multiple types of exceptions -- [see this question](http://stackoverflow.com/questions/6470428/catch-multiple-exceptions-in-one-line-except-block) – jedwards Mar 20 '15 at 11:17
  • 1
    O/T, but you should consider reading [the style guide](http://www.python.org/dev/peps/pep-0008/). – jonrsharpe Mar 20 '15 at 11:20

1 Answers1

8

The syntax for multiple exceptions is:

except (RuntimeError, TypeError, NameError):

and is not a recognised part of this syntax; IndexError and ValueError evaluates to ValueError, so any IndexErrors will not be caught.

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
deceze
  • 510,633
  • 85
  • 743
  • 889
  • 5
    `IndexError and ValueError` returns `ValueError` (the `and` operator returns the result of the right-hand expression if the left-hand expression is true-ish; type objects are always considered true) – Martijn Pieters Mar 20 '15 at 11:18
  • Ah, there you go. Learned something new. :o) – deceze Mar 20 '15 at 11:19
  • Thanks @deceze for this. There were a few other errors with my code but I've fixed them myself. Again thanks for the help Devilb77 – Ben Mar 20 '15 at 13:06