我有一个关于简单搜索确认功能的疑问,其中代码在列表中查看某些值并返回搜索结果,是否找到了任何东西。例如,找到以下代码打印。
我使用了"找到"的变量,并为此分配了该变量,但我回想起在某个地方没有使用另一个变量来实现此目的的学习,而是使用了一个简单的if If and logic。我该如何合并"否则"并在删除变量"找到"时仍使其工作?
def search_confirm_tool(arr,to_find):
found=False
for i in range(len(arr)):
if to_find == arr[i]:
print("Found")
found=True
break
if found!=True:
print("Not found")
search_confirm_tool(["bob","joe","dave"],"joe")
for loop有一个其他子句:
def search_confirm_tool(arr,to_find):
for x in arr:
if to_find == x:
print("Found")
break
else:
print("Not found")
当您不从中 break
时,它将被执行。
def search_confirm_tool(arr,to_find):
if to_find in arr:
print("found")
else:
print("not found")
search_confirm_tool(["bob","joe","dave"],"joe")
您可以使用上述代码来完成此任务。
谢谢