尝试除了在while循环中

时间:2015-03-20 11:13:11

标签: python while-loop try-catch

我在try except循环中遇到while问题。我还是比较新的编程,这是我的A2 Comp4项目的一部分。

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

我一直收到这个错误:

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

我的问题是,我认为我在IndexError中排除了try except。它应该是抛出这个问题。

整个代码应该检查首字母(在另一个函数中输入)是否包含任何数字。

1 个答案:

答案 0 :(得分:8)

The syntax for multiple exceptions是:

except (RuntimeError, TypeError, NameError):

and不是此语法的公认部分; IndexError and ValueError评估为ValueError,因此不会抓住任何IndexError