1

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: 
Bach
  • 6,145
  • 7
  • 36
  • 61
user3165683
  • 347
  • 1
  • 9
  • 28
  • 1
    You are performing a try...except... operation without choosing what Exceptions to catch. This will stop you from manually exiting the program too (with a KeyboardInterrupt). You should **never** have a general `except` clause. – Ffisegydd Apr 17 '14 at 14:40
  • 2
    change `search` to `select`. Voting to close as typo. – anon582847382 Apr 17 '14 at 14:41
  • Note: I have updated my answer. Please see the suggestion – sshashank124 Apr 17 '14 at 14:42

1 Answers1

4

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:")
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
sshashank124
  • 31,495
  • 9
  • 67
  • 76
  • 1
    It is still worth covering the `input` with a `try`, in case they enter something that can't be made an `int` - I would suggest putting the rest in the `else` block of that `try`. – jonrsharpe Apr 17 '14 at 14:44
  • @jonrsharpe, I'm not sure what you mean by the `else` block. Can you please explain? Please go ahead and append to my answer if you wish and are willing to. Thank you. – sshashank124 Apr 17 '14 at 14:46