如何检查用户输入是否是我作为选项给出的确切字符串



用户可以选择字符串。我只想确保用户选择我提供的特定字符串。

这是我的代码的样子:

category_choice = input("Which category would you like to search with? Here are the choice: n"
"'Name', 'Phone number','Class time','Class duration'n")
while category_choice != "Name" or "Phone number" or "Class time" or "Class duration":
category_choice = input("Please specifically write one of the choices of the list.nInput: ")

一旦用户输入正确,我希望它退出 while 循环并继续,但它似乎永远持续下去。

我做错了什么?

当你写一个隔离的字符串时,如"Name"或"Phone"或"Other thing",返回值将为True,因为bool('anyword') == True, and bool("") == False

尝试

category_choice = input("Which category would you like to search with? Here are the choice: n""'Name', 'Phone number','Class time','Class duration'n")
while category_choice not in ["Name","Phone number","Class time","Class duration"]:
category_choice = input("Please specifically write one of the choices of the list.nInput: ")

您必须更改条件:

while category_choice not in ["Name", "Phone number", "Class time", "Class duration"]:

while category_choice != "Name" or category_choice != "Phone number" or category_choice !=  "Class time" or category_choice !=  "Class duration":
while category_choice != "Name" or "Phone number" or "Class time" or "Class duration":

尝试打印此条件以检查它是否返回 true 或 false 。输入时,仅检查第一个条件,其余时,它将category_choice分配为"电话号码"。

while category_choice != "Name" and category_choice != "Phone number" and  category_choice != "Class time" and category_choice != "Class duration":
category_choice = input("Please specifically write one of the choices of the list.nInput: ") 

您应该使用 and 而不是 or ,因为输入值将始终为"姓名"、"电话号码"、"上课时间"、"上课时间"。让输入category_choice为"名称",当它使用或该条件将始终为真时,因为category_choice != "电话号码",对于其他情况也是如此。

希望对你有帮助

相关内容

  • 没有找到相关文章

最新更新