我整天都在挣扎,我似乎无法解决这个问题。我应该编写一个Exception类,然后在迭代期间提升它并继续我离开的地方。
class OhNoNotTrueException(Exception):
"""Exception raised when False is encountered
Attributes:
message -- explanation of the error"""
def __init__(self, value):
self.value = value
am_i_true_or_false = [True, None, False, "True", 0, "", 8, "False", "True", "0.0"]
try:
for i in am_i_true_or_false:
if i is False:
raise OhNoNotTrueException(i)
continue #<--this continue does not work
else:
print(i, "is True")
except OhNoNotTrueException as e:
print(e.value, "is False")
然而,即使在继续之后,我也无法将迭代恢复到最后一个索引。我不确定这是否是唯一的方法,但我在这里打破了我的头脑。有人想破解它吗?
我应该得到以下输出:
确实如此。
无为假
错误是假的
确实如此。
0是假的
是假的
8是真的。
错误是真的。
确实如此。
0.0为真。
答案 0 :(得分:3)
永远不会触发异常之后的所有内容,并且您将被带到循环之外,就好像try-block中的所有内容都不会发生一样。因此,您需要在循环内尝试/ except:
In [5]: for i in am_i_true_or_false:
...: try:
...: if i is False:
...: raise OhNoNotTrueException(i)
...: else:
...: print(i, "is not False")
...: except OhNoNotTrueException as e:
...: print(e.value, "is False")
...:
True is not False
None is not False
False is False
True is not False
0 is not False
is not False
8 is not False
False is not False
True is not False
0.0 is not False
注意如果你的try-block包含循环会发生什么:
In [2]: try:
...: for i in am_i_true_or_false:
...: if i is False:
...: raise Exception()
...: else:
...: print(i,"is not False")
...: except Exception as e:
...: continue
...:
File "<ipython-input-2-97971e491461>", line 8
continue
^
SyntaxError: 'continue' not properly in loop
答案 1 :(得分:1)
你应该在try / except块之外进行循环。然后,try catch将检查一个单独的列表条目,然后循环将继续下一个:
for i in am_i_true_or_false:
try:
if i is False:
raise OhNoNotTrueException(i)
else:
print("{} is True".format(i))
except OhNoNotTrueException as e:
print("{} is False".format(e.value))
执行此操作的方式,循环执行直到第一个异常,然后执行except块并且程序结束。在这种情况下未达到continue
,因为您抛出了将在except块中捕获的异常。