문제

My code is not allowing me to break out of the infinite loop, and therefore exit the program. Here is my code:

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:")

Here is what the input/output looks like:

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: 
도움이 되었습니까?

해결책

It should be select not 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:")

Also, I suggest you use an else statement instead of a generic except clause as follows:

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:")
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top