简体   繁体   中英

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.

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 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}")
  • You must either write if food:="Fish" and food !="Eggs": or if food not in ("Fish","Eggs"):

You could do if food not in ["Fish", "Eggs"] .

The problem is, you are evaluating food != "Fish" and "Eggs" . The latter evaluates to True in a boolean context. Therefore, the whole statement is evaluated to 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.

if food != "Fish" and food != "Eggs":

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM