我有一个基本程序,它接受一个现有列表,要求用户输入,并在列表中搜索用户输入的元素。我希望它找到它所在的索引,并打印索引。当我输入一个不在列表中的值时,我收到错误消息:“ValueError: 7 is not in list”
如何阻止程序给出错误消息,或让用户知道该值不在列表中?
编辑,添加代码:
L = [4, 10, 4, 2, 9, 5, 4]
L2 = []
print ("L = ",L)
x = input("Enter an element to search for in the list: ")
x = int(x)
m = L.index(x)
L2.append(m)
print("Found occurences at indexes: ",L2)
我只是试图找到所有出现的索引,如果没有,则打印一条错误消息。
请您参考如下方法:
为此,您可以使用 try 和 except 来避免错误。例如看下面的代码:
>>> list_1=[1,2,3,4,5]
>>> input=raw_input("Enter the number:")
Enter the number: 5
>>> try:
... index=list_1.index(int(input))
... print "The index is %s" %index
... except ValueError:
... print "The number is not in the list"
...
The index is 4
如果您再次执行它并输入不在列表中的值,您将得到您使用 except 处理过的消息。
Enter the number:7
The number is not in the list
