我不知道该给标题起什么名字。但我对一般编程很陌生,并且我正在使用 python。我的问题是,为什么只写 return 而不是一堆 if 和 else 语句的效果完全相同。
#Multiple lines
def parrot_trouble(talking, hour):
if talking:
if hour <7 or hour >20:
return True
return False
#One line
def parrot_trouble(talking, hour):
return (talking and (hour < 7 or hour > 20))
这两个代码产生完全相同的结果..但是为什么呢?抱歉,我是个新人
最佳答案
Both these codes yield the exact same results
这是不正确的。仅当输入为特定类型时才是正确的。考虑这个简单的反例:
def parrot_trouble1(talking, hour):
if talking:
if hour < 7 or hour > 20:
return True
return False
def parrot_trouble2(talking, hour):
return (talking and (hour < 7 or hour > 20))
parrot_trouble1([], 0) # False
parrot_trouble2([], 0) # []
But note and
/ or
are designed this way:
Note that neither
and
noror
restrict the value and type they return toFalse
andTrue
, but rather return the last evaluated argument.
parrot_trouble2
表现出短路现象。我们假设talking
是一个 boolean 输入。如果talking
是 False
,表达式短路并返回 False
。如果talking
是 True
, parrot_trouble2
将返回True
或False
取决于 hour
的值.
parrot_trouble1
不会短路,但结果是一样的。如果talking
是 boolean 值且 False
,函数返回False
。如果talking
是 True
,那么第二个标准hour < 7 or hour > 20
经测试。如果未指定条件,则由于没有返回任何内容,Python 会移动到 if
的外部和之后。致return False
的声明.
关于python - 一行与多行的 boolean 比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52802145/