简体   繁体   中英

How to handle errors in Python

I am new to Python and this time i would like to practice error handling in Python. This is my exercise: I am having 2 lists: l1 = [1, 2, 3, 4, 5, 6] si l2 = [0, 1, '0', '2', 'john', 4] . And I would like to iterate through l1 and for each index i want its element to be divided by the element on the same index in l2. If i am having an error, i would like to print the elements from each list as well as the index.

I am doing something wrong. Could you help me? Please find my code below:

l1 = [1, 2, 3, 4, 5, 6]
l2 = [0, 1, '0', '2', 'john', 4]

try:
    x=0
    float(x)
    for indexl1, elementl1 in enumerate(l1):
        for indexl2, elementl2 in enumerate(l2):
            x = elementl1 / elementl2
            print('-------')
except ValueError as ve:
    print('error, not number', elementl1, elementl2, indexl1, ve)
except ZeroDivisionError as zde:
    print('error, zerodiv', elementl1, elementl2, indexl1, zde)
else:
    print(x)

You just have to move the try except inside the inner loop:

l1 = [1, 2, 3, 4, 5, 6]
l2 = [0, 1, '0', '2', 'john', 4]

for indexl1, elementl1 in enumerate(l1):
    for indexl2, elementl2 in enumerate(l2):
        try:
            x = elementl1 / elementl2
            print('-------')
        except ValueError as ve:
            print('error, not number', elementl1, elementl2, indexl1, ve)
        except ZeroDivisionError as zde:
            print('error, zerodiv', elementl1, elementl2, indexl1, zde)
        else:
            print(x)

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