如何在列表中调用函数、捕获异常并在必要时重复函数?

我试图让用户输入一些问题,这些问题都具有相同的标准(要求用户从 1 到 10 打分)。


我将每个问题都作为一个函数,并使用 for 循环按照它们在列表中的位置顺序调用它们。在 for 循环中,我有一个 while 循环检查它们是否有异常。但是,Python 在检查异常之前会运行所有函数。我希望它运行第一个函数,检查错误,然后运行第二个函数。我该如何实施?


这是我的代码:


interest_list = []

function_list = [cheese(), wine(), beer(), spirits(), \

              coffee(), chocolate()]

for afunc in function_list :

    loop_check = None

    while loop_check == None :

        try :

            if int(afunc) <= 5 and int(afunc) >= -5 :

                interest_list.append(afunc)

            else :

                raise RangeQuestionsError


        except (ValueError, RangeQuestionsError) :

            print(afunc, " is not a valid choice. Try again.", sep="")

            loop_check = None


天涯尽头无女友
浏览 160回答 2
2回答

慕少森

您在初始化不正确的列表时正在调用函数尝试以下代码interest_list = []function_list = [cheese, wine, beer, spirits, \&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; coffee, chocolate]for afunc in function_list :&nbsp; &nbsp; loop_check = None&nbsp; &nbsp; while loop_check == None :&nbsp; &nbsp; &nbsp; &nbsp; try :&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if int(afunc()) <= 5 and int(afunc()) >= -5 :&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; interest_list.append(afunc)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; else :&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; raise RangeQuestionsError&nbsp; &nbsp; &nbsp; &nbsp; except (ValueError, RangeQuestionsError) :&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; print(afunc, " is not a valid choice. Try again.", sep="")&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; loop_check = None

慕田峪9158850

您可以将列表作为字符串列表,然后使用eval函数对其进行评估。请记住,您还必须定义函数。interest_list = []function_list = ['cheese()', 'wine()', 'beer()', 'spirits()', 'coffee()', 'chocolate()']for func in function_list :&nbsp; &nbsp; afunc = eval(func)&nbsp; &nbsp; loop_check = None&nbsp; &nbsp; while loop_check == None :&nbsp; &nbsp; &nbsp; &nbsp; try :&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if int(afunc) <= 5 and int(afunc) >= -5 :&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; interest_list.append(afunc)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; else :&nbsp; &nbsp; &nbsp; &nbsp; raise RangeQuestionsError&nbsp; &nbsp; except (ValueError, RangeQuestionsError) :&nbsp; &nbsp; &nbsp; &nbsp; print(afunc, " is not a valid choice. Try again.", sep="")&nbsp; &nbsp; &nbsp; &nbsp; loop_check = None
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python