打破无限循环

时间:2014-04-17 14:37:39

标签: python loops python-3.x infinite-loop break

我的代码不允许我突破无限循环,因此退出程序。这是我的代码:

while True:
        print("\n1. Surname\n2. D.O.B\n3. Quit")
        try:
            select = int(input("Please select an option: "))
            if select == 1:
                surnameSearch()
            elif select == 2:
                DOB_search(BkRdr)
            elif search == 3:
                break
        except:
            print("That was an incorrect option, please try again:")

这是输入/输出的样子:

1. Surname
2. D.O.B
3. Quit
Please select an option: 3
That was an incorrect option, please try agan:

1. Surname
2. D.O.B
3. Quit
Please select an option: 

1 个答案:

答案 0 :(得分:4)

应该是select而不是search

while True:
    print("\n1. Surname\n2. D.O.B\n3. Quit")
    try:
        select = int(input("Please select an option: "))
        if select == 1:
            surnameSearch()
        elif select == 2:
            DOB_search(BkRdr)
        elif select == 3:
            break
    except:
        print("That was an incorrect option, please try again:")

另外,我建议您使用else语句而不是通用except子句,如下所示:

while True:
    print("\n1. Surname\n2. D.O.B\n3. Quit")
    try:
        select = int(input("Please select an option: "))
    except ValueError:
        print("Not a valid input")
    else:
        if select == 1:
            surnameSearch()
        elif select == 2:
            DOB_search(BkRdr)
        elif select == 3:
            break
        else:
            print("That was an incorrect option, please try again:")