python - 一行与多行的 boolean 比较

标签 python python-3.x boolean

我不知道该给标题起什么名字。但我对一般编程很陌生,并且我正在使用 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 nor or restrict the value and type they return to False and True, but rather return the last evaluated argument.

parrot_trouble2表现出短路现象。我们假设talking是一个 boolean 输入。如果talkingFalse ,表达式短路并返回 False 。如果talkingTrue , parrot_trouble2将返回TrueFalse取决于 hour 的值.

parrot_trouble1不会短路,但结果是一样的。如果talking是 boolean 值且 False ,函数返回False 。如果talkingTrue ,那么第二个标准hour < 7 or hour > 20经测试。如果未指定条件,则由于没有返回任何内容,Python 会移动到 if 的外部和之后。致return False的声明.

关于python - 一行与多行的 boolean 比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52802145/

相关文章:

python - 如何将带有索引列表的字典映射到新变量

python - 升级过时的软件包后 pip 需要密码

javascript - boolean 变量设置为 true 后警报为 false

powershell - 将 "Yes"或 "No"转换为 boolean 值

python - 从脚本目录/当前目录运行Python脚本

python - Python如何管理int和long?

python3 : Using ternary operator in map, 它将返回 None

python - 没有提供任何参数时,LassoCV 中的参数选择如何工作?

.net - AutoResetEvent 类型是原子开关的合适选择吗?

python - 表面动画和使用 matplotlib 保存