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

Pap*_*gye 2 python

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

如何在其中编写if语句or

例如:

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."
Run Code Online (Sandbox Code Playgroud)

Joh*_*ooy 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."
Run Code Online (Sandbox Code Playgroud)

你也可以在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."
Run Code Online (Sandbox Code Playgroud)

  • @marr这是一个非常微不足道的问题,我认为我们不需要开始重构它以使其更具"功能性" (5认同)

Dan*_*man 11

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

if raw_input == "dog" or raw_input == "cat" or raw_input == "small bird":
Run Code Online (Sandbox Code Playgroud)

但是,进行这种特殊比较的更好方法是in:

if raw_input in ("dog", "cat", "small bird"):
Run Code Online (Sandbox Code Playgroud)