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



我正在尝试让用户输入许多具有相同标准的问题(要求用户对 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

您在初始化不正确的列表时调用函数请尝试以下代码

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

您可以将列表作为字符串列表,然后使用eval函数对其进行评估。

请记住,您还必须定义函数。

interest_list = []
function_list = ['cheese()', 'wine()', 'beer()', 'spirits()', 'coffee()', 'chocolate()']
for func in function_list :
afunc = eval(func)
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

最新更新