Matt
Matt

Reputation: 3

Except block always being thrown even after going through the try block and rest of the program?

I check to see if input can be changed into an integer if it can't it starts back from the beginning of UI(). I followed it through pycharm's debugger and it will pass the try, but when I try using 4 to exit.It will go through to the end, and then go back up to the except block.

I think the parts I commented after are the only relevant parts. Thanks for any help.

    def UI():
    global exitBool
    global newBool

    if not TV.tvList:
       tv = TurnOnTV()
    if TV.tvList:
        l = list(TV.tvList.keys())
        tv = TV.tvList.get(l[0])

    print("1)change channel\n2)change volume\n3)Turn on another TV\n4)Exit\n5)Choose TV")   #print accepted answers

    choice = input()

    try:
        choice = int(choice)                #try block and exception block
    except:
        print("\nInvalid Choice\n")
        UI()

    choice = int(choice)

    if choice == 1:
        if tv:
            tv.changechannel(input("enter channel: "))
        else:
            print('sorry no tvs are available\n')
    elif choice == 2:
        if tv:
            tv.changevolume(input("Enter in volume: "))
        else:
            print('Sorry no Tvs available')

    elif choice == 3:
        TurnOnTV()
    elif choice == 4:
        exitBool = True     # exit bool to exit main loop
    elif choice == 5:
       tv = ChooseTV(input("Enter in TV name: "))
    else:
        print("Invalid Choice")

    if tv:
        tv.display()

def Main():
    while exitBool == False:       #Main Loop
        UI()

Upvotes: 0

Views: 40

Answers (1)

Emanuele Paolini
Emanuele Paolini

Reputation: 10162

When you catch the error and print "invalid choice" you must not call UI() again. That way you are making a recursive call, and when the inner UI() terminates the code goes on on the outer one.

Use a "while" statement to repeat a block of code until the user makes a valid choice.

Upvotes: 1

Related Questions