def active_check(active):
for i in range(0, (len(active_data)-1)):
if active == active_data[i][0]:
raise active_Cert
break
else:
print("TTTTTTTTTTTTTTTTTTTT")
return active
try:
while True:
active = active_check(input("Enter state"))
except active_Cert:
pass
print(active)
我进行了此设置,用户输入一个数字,然后扫描CSV以查找该数字是否与第一个“列”中的任何数据匹配。如果找到一个,则应引发一个异常,该异常退出该函数所在的while循环,并且确实如此。问题在于,最终的打印语句会打印倒数第二个输入的变量(假设存在多个不正确的条目)
尽管我找不到解决这个问题的好方法,但我能明白为什么会这样
答案 0 :(得分:2)
可能的解决方案是返回带有active
变量的某些变量,而不是引发异常。
考虑以下代码,我添加了to_continue
变量并删除了例外部分:
def active_check(active):
for i in range(0, (len(active_data)-1)):
if active == active_data[i][0]:
return active, False
else:
print("TTTTTTTTTTTTTTTTTTTT")
return active, True
to_continue = True
while to_continue:
active, to_continue = active_check(input("Enter state"))
print(active)