Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to pass the exception in for loop

a = [2,"cat",None,1]

try:
    for i in a:
        print(int(i))
except Exception as e:
    print(e)
    pass

How to pass the exception in for loop. I need to put for loop inside try and need to pass the value in exception and get the value 1 from the list

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

You can modify the code as follows to pass the exception in the for loop and still get the value 1 from the list:

a = [2,"cat",None,1]

for i in a:
    try:
        print(int(i))
    except Exception as e:
        print(e)
        pass

This way, the try block will be inside the for loop, and the except block will handle any exceptions that are raised when trying to convert the current element i to an integer. If an exception is raised, the pass statement will be executed, allowing the loop to continue to the next iteration, without stopping the whole loop.

An alternative way would be to use a list comprehension and filter out the elements that can’t be converted to int.

a = [2,"cat",None,1]

valid_list = [i for i in a if isinstance(i, (int,float))]
print(valid_list)

This way, the final list will only contain the values that were successfully casted to int and the non-int values will be filtered out.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading