我的“if”声明中的“或”有什么问题?

时间:2010-08-02 14:39:07

标签: python

我试过谷歌,但我找不到这个简单问题的答案。 我讨厌自己无法解决这个问题,但我们走了。

如何在其中编写带or的if语句?

例如:

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."

5 个答案:

答案 0 :(得分:17)

您可以将允许的动物放入tuple然后使用in搜索匹配

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."

你也可以在这里使用set,但我怀疑这会改善这么少的允许动物的表现

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."

答案 1 :(得分:11)

如果你想使用or,你需要每次都重复整个表达式:

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

但进行此特定比较的更好方法是使用in

if raw_input in ("dog", "cat", "small bird"):

答案 2 :(得分:1)

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.

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.

答案 3 :(得分:0)

你可以这样做

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

答案 4 :(得分:0)

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.")