除了通过try块和程序的其余部分后总是抛出块之外?

2024-09-27 20:19:29 发布

您现在位置:Python中文网/ 问答频道 /正文

我检查输入是否可以更改为整数,如果不能,则从UI()的开头开始。我跟随它通过pycharm的调试器,它将通过try,但是当我尝试使用4退出时,它将通过到最后,然后返回到except块

我想我评论的部分是唯一相关的部分。谢谢你的帮助

    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()

Tags: uiinputifdeftvglobalelseprint
1条回答
网友
1楼 · 发布于 2024-09-27 20:19:29

当捕捉到错误并打印“invalid choice”时,不能再次调用UI()。这样,您就可以进行递归调用,当内部UI()终止时,代码将在外部UI()上继续

使用“while”语句重复一段代码,直到用户做出有效的选择

相关问题 更多 >

    热门问题