-1

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.

Si Zhang
  • 37
  • 1
  • 1
  • 4

2 Answers2

2

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)
CrizR
  • 688
  • 1
  • 6
  • 26
0

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.

HunterM267
  • 199
  • 1
  • 12