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")
If I run this code, it asks to enter two lists one by one. I've put an exception in case any list with any non-integer-element is input. Now if I input this list [1,b,2,4]
on the first time, the error immediately shows up. I want this error message after I input both the lists.
CodePudding user response:
You can simply make the following :
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")
But keep in mind that this doesn't prevent passing anything other than numbers, it just prevents passing an element containing a syntax error (like you did in the exemple, as a
isn't valid, but "a"
is).
So you will have to add an except
for TypeError
, and change the message for your 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")