我希望在输入两个列表后打印错误消息

I want the error message to print after I input the two lists

try:

    list_one = eval(input())
    list_two = eval(input())

    sum = 0
    newlis = []

    for i in range(len(list_one)):
        newlis.append(list_one[i] * list_two[i])

    for i in newlis:
        sum += i

    print(sum)

except IndexError:
    print("Index out of bound")

except NameError:
    print("The list has some non number values")

如果我运行这段代码,它会要求一一输入两个列表。如果输入任何包含任何非整数元素的列表,我会设置一个例外。现在,如果我第一次输入这个列表 [1,b,2,4],错误会立即出现。输入两个列表后,我想要此错误消息。

您可以简单地进行以下操作:

try:

    list_one, list_two = input(), input()
    list_one, list_two = eval(list_one), eval(list_two)

    sum = 0
    newlis = []

    for i in range(len(list_one)):
        newlis.append(list_one[i] * list_two[i])

    for i in newlis:
        sum += i

    print(sum)

except IndexError:
    print("Index out of bound")

except NameError:
    print("The list has some non number values")

但请记住,这不会阻止传递数字以外的任何内容,它只会阻止传递包含语法错误的元素(就像您在示例中所做的那样,因为 a 无效,但是 "a" 是)。

因此您必须为 TypeError 添加 except,并更改 NameError 的消息:

try:

    list_one, list_two = input(), input()
    list_one, list_two = eval(list_one), eval(list_two)

    sum = 0
    newlis = []

    for i in range(len(list_one)):
        newlis.append(list_one[i] * list_two[i])

    for i in newlis:
        sum += i

    print(sum)

except IndexError:
    print("Index out of bound")

except NameError:
    print("The given object is invalid")

except TypeError:
    print("The object passed isn't a list of numbers")