Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/298.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python在for循环中使用try/except_Python_Try Catch - Fatal编程技术网

Python在for循环中使用try/except

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') 我在条目中只有值,错误仍然为空。如何修复我的代码。

我不熟悉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')

我在条目中只有值,错误仍然为空。如何修复我的代码。谢谢。

除了修复缩进,对于您正在做的事情,您只需在
的基础上使用
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。