如何在 Python 3 的列表中搜索整数



函数"搜索整数"(或编码中的searchArray(应该让用户输入一个值,例如4,如果4在列表中,那么它将返回一条消息,说"是的,4在此列表中。我很确定我的编码是正确的...但消息不会显示

def searchArray(array):
message = ""
length = len(array)
numStr = getUserText("Enter a positive integer to search for")
num = checkInt(numStr, "Sorry that's not an integer, try again")
try:
array.index(numStr)
message = "The number " + str(index) + " was found in the array."
except ValueError:
message = str(numStr) + " was not found." + " "
return message

^ 当我打印消息时,什么都没有显示,它是空白的。

您的数组包含整数,但您正在搜索numStr,其中包含一个字符串。您应该搜索num.

另外,没有变量index,你的意思是numStr.

try:
array.index(num)
message = "The number " + numStr + " was found in the array."
except ValueError:
message = numStr + " was not found." + " "

in关键字可让您检查成员资格。适用于列表、集合、字典等。

def searchArray(array):
length = len(array)
numStr = getUserText("Enter a positive integer to search for")
num = checkInt(numStr, "Sorry that's not an integer, try again")
if num in array:
return f"The number {num} was found, at index {array.index(num)}."
else:
return f"The number {num} was not found."

最新更新