我知道也有类似的主题,我检查了每个主题,但是在这里我仍然无法弄清楚自己在做什么错:
我有一个列表(待办事项),并希望使用以下功能搜索ID:
def searchID():
todo_id_search = input('Please input ID:')
if todo_id_search in todos:
print(todo_id_search)
else:
print("ID not in list")
它以某种方式永远不会返回ID(即使它在列表中)。应该可以搜索那样的ID或我认为错了吗?我正在使用Python 3.7。
谢谢!
我认为这是由于datatype
您的input
数据与要检查的列表元素之间的不匹配引起的。
例如:如果您列表中的元素todos
是integer
数据,则
todo_id_search = input('Please input ID:')
这todo_id_search
始终是一个string
为input
总是返回string
类型的数据,因此没有你if
的代码块string
和int
所不能比拟的,对于故障排除您可以通过使用检查它的类型
print (type(todo_id_search))
并且在确认了列表todos
元素的类型之后,您可以在用户输入数据中执行必要的类型转换,即todo_id_search
使用int(todo_id_search)
或float(todo_id_search)
在您的if
条件下进行。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句