简体   繁体   中英

Python use try/except in for loop

I'm new to python exception. I want to try catch/except in a for loop, how can I implement the code. Thank you.

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')

I only have value in entry and error is still empty. How can I fix my code. Thank you.

A try-except is used to catch exceptions. The code within your try has no reason to throw an exception. You can do this instead... although this is not a good use case for a try-except. You should really just be using an 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)

In addition to fixing the indentation, for what you're doing, you could simply just use else in addition to your if :

for nums in b:
    for num in nums:
        if a-num == 3:
            entry.append("yes")
        else:
            error.append('no')

As others said, it's never a good idea to write except without including the exception you're looking for. This post gives some good explanation why.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM