Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/315.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 什么';“这是怎么回事?”;或;在我的;如果;陈述_Python - Fatal编程技术网

Python 什么';“这是怎么回事?”;或;在我的;如果;陈述

Python 什么';“这是怎么回事?”;或;在我的;如果;陈述,python,Python,我试过谷歌,但我找不到这个简单问题的答案。 我恨我自己没能弄明白,但我们走吧 如何编写包含或的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." 您可以将允许的动物放入一个列表中,然后使用中的搜索

我试过谷歌,但我找不到这个简单问题的答案。 我恨我自己没能弄明白,但我们走吧

如何编写包含
的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."

您可以将允许的动物放入一个列表中,然后使用
中的
搜索匹配项

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."
您也可以在此处使用,但我怀疑它是否会提高如此少量允许动物的性能

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 raw_input == "dog" or raw_input == "cat" or raw_input == "small bird":
但更好的方法是使用
中的

if raw_input in ("dog", "cat", "small bird"):
你可以这样做

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

不是很“pythonic”,我写过这样的代码,但我不会推荐给新的程序员。假设raw_输入应该是函数调用raw_input(),您不会想调用它3次+1。大多数pythonic解决方案都可以变得更具功能性,不过。@marr这是一个非常简单的问题,我不认为我们需要开始重构它来让它更“功能化”@marr75,请随意发布一个更功能化的答案:)@Michael我并不是说它需要,只是最近“pythonic”似乎开始有更多的功能性编程内涵,这可能只是我的观点@gnibbler我能想到的唯一功能代码(映射然后还原)可能更难阅读。您的示例代码是“或”对字符串进行加密,这不是一个合法的操作。@marr它实际上在执行
(raw\u input='dog')或'cat'或'small bird'
,因此如果
raw\u input='dog'
,它将返回
True
,或者
cat
otherwiseOops,您是对的,它将始终执行。它正在对字符串进行or'ing运算,但每次都会计算为“cat”,因为cat是一个字符串并且不是空的,所以它将被视为true。
if raw_input in ("dog", "cat", "small bird"):
 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.")