[英]How to check that a string is equal to one of two strings in Python
This is my code:这是我的代码:
print("What is your Name")
user_name = input("User Name: ")
print(f"Hello {user_name} please choose a dish and a drink from this menu : \n Fish \t Eggs \n Water \t Juice")
food = input("Please input your desired dish: ")
drink = input("Please input your desired drink: ")
if food != "Fish" or "Eggs":
print("Please input a correct dish or drink")
else:
print(f"{user_name} your desired drink is {drink} and your desired dish is {food}")
The main problem is the final part.主要问题是最后一部分。 I'm trying to say "if food is not equal to Fish or Eggs print the error message but if it is print the success message".
我想说“如果食物不等于鱼或鸡蛋,则打印错误消息,但如果它打印成功消息”。 But, if you copy the code and follow it at the end it always prints the error message.
但是,如果您复制代码并在最后跟随它,它总是会打印错误消息。
print("What is your Name")
user_name = input("User Name: ")
print(f"Hello {user_name} please choose a dish and a drink from this menu : \n Fish \t Eggs \n Water \t Juice")
food = input("Please input your desired dish: ")
drink = input("Please input your desired drink: ")
if food not in ("Fish","Eggs"):
print("Please input a correct dish or drink")
else:
print(f"{user_name} your desired drink is {drink} and your desired dish is {food}")
if food:="Fish" and food !="Eggs":
or if food not in ("Fish","Eggs"):
if food:="Fish" and food !="Eggs":
或者if food not in ("Fish","Eggs"):
You could do if food not in ["Fish", "Eggs"]
. if food not in ["Fish", "Eggs"]
你可以这样做。
The problem is, you are evaluating food != "Fish"
and "Eggs"
.问题是,您正在评估
food != "Fish"
和"Eggs"
。 The latter evaluates to True
in a boolean context.后者在 boolean 上下文中评估为
True
。 Therefore, the whole statement is evaluated to True
.因此,整个语句被评估为
True
。
if food != "Fish" or "Eggs":
your input will always make one of the above condition true, because you have option to input either Fish or Eggs, so instead of or
you need to use and
condition with explicit check for both items to satisfy your condition.您的输入将始终使上述条件之一为真,因为您可以选择输入 Fish
or
Eggs,因此您需要使用and
condition 来明确检查这两个项目以满足您的条件。
if food != "Fish" and food != "Eggs":
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.