简体   繁体   中英

What's wrong with the “or” in my “if” statement?

I've tried Google, but I can't find the answer to this simple question. I hate myself for not being able to figure this out, but here we go.

How do I write an if statement with or in it?

For example:

if raw_input=="dog" or "cat" or "small bird":
    print "You can have this animal in your house"
else:
    print "I'm afraid you can't have this animal in your house."

You can put the allowed animals into a tuple then use in to search for a match

if raw_input() in ("dog", "cat", "small bird"):
    print "You can have this animal in your house"
else:
    print "I'm afraid you can't have this animal in your house."

You can also use a set here, but I doubt it would improve performance for such a small number of allowed animals

desired_animal = raw_input()
allowed_animals = set(("dog", "cat", "small bird"))
if desired_animal in allowed_animals:
    print "You can have this animal in your house"
else:
    print "I'm afraid you can't have this animal in your house."

If you want to use or , you need to repeat the whole expression each time:

if raw_input == "dog" or raw_input == "cat" or raw_input == "small bird":

But a better way to do this particular comparison is with in :

if raw_input in ("dog", "cat", "small bird"):
if (raw_input=="dog") or (raw_input == "cat") or (raw_input == "small bird"):
  print You can have this animal in your house
else:
  print I'm afraid you can't have this animal in your house.

or

if raw_input in ("dog", "cat", "small bird"):
  print You can have this animal in your house
else:
  print I'm afraid you can't have this animal in your house.

你可以这样做

 if raw_input=="dog" or raw_input=="cat" or raw_input=="small bird":
goodanimals= ("dog" ,"cat","small bird")
print("You can have this animal in your house" if raw_input().strip().lower() in goodanimals
      else "I'm afraid you can't have this animal in your house.")

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