Python在for循环中使用try/except
我不熟悉python异常。我想尝试catch/除了在for循环中,如何实现代码。多谢各位Python在for循环中使用try/except,python,try-catch,Python,Try Catch,我不熟悉python异常。我想尝试catch/除了在for循环中,如何实现代码。多谢各位 a=5 b=[[1,3,3,4],[1,2,3,4]] entry=[] error=[] for nums in b: try: for num in nums: if a-num==3: entry.append("yes") except: error.append('no') 我在条目中只有值,错误仍然为空。如何修复我的代码。
a=5
b=[[1,3,3,4],[1,2,3,4]]
entry=[]
error=[]
for nums in b:
try:
for num in nums:
if a-num==3:
entry.append("yes")
except:
error.append('no')
我在条目中只有值,错误仍然为空。如何修复我的代码。谢谢。除了修复缩进,对于您正在做的事情,您只需在
的基础上使用else
,如果
:
a=5
b=[[1,3,3,4],[1,2,3,4]]
entry=[]
error=[]
for nums in b:
try:
for num in nums:
if a-num==3:
entry.append("yes")
except:
error.append('no')
for nums in b:
for num in nums:
if a-num == 3:
entry.append("yes")
else:
error.append('no')
正如其他人所说,编写
(除了)而不包含您正在寻找的例外情况,这从来都不是一个好主意。给出了一些很好的解释。try except用于捕获异常。try中的代码没有理由引发异常。你可以这样做。。。尽管这不是一个很好的尝试用例。你真的应该使用if-else
if __name__ == '__main__':
a = 5
b = [[1, 3, 3, 4], [1, 2, 3, 4]]
entry = []
error = []
for nums in b:
for num in nums:
try:
if a - num == 3:
entry.append("yes")
else:
raise ValueError
except:
error.append("no")
print(entry, error)
除了:
很少是个好主意。这里没有例外。如果您想在未执行分支时执行某项操作,那就是else
,不要尝试except。