用python中的函数返回true或false

时间:2019-07-09 18:27:47

标签: python python-3.x boolean-logic

您能解释一下我的代码为什么错误吗? 另外,我不太了解解决方案代码的工作原理,请解释一下。 这是练习: 给定2个int值,如果一个为负且一个为正,则返回True。除非参数“ negative”为True,否则仅当两个参数均为负时才返回True。

pos_neg(1, -1, False) → True
pos_neg(-1, 1, False) → True
pos_neg(-4, -5, True) → True

这是我的代码:

def pos_neg(a, b, negative):
  if (a < 0 and b > 0) or (a > 0 and b < 0):
    return True
  if negative==True:
    if a < 0 and b < 0:
      return True
  return False

这是解决方案:

def pos_neg(a, b, negative):
  if negative:
    return (a < 0 and b < 0)
  else:
    return ((a < 0 and b > 0) or (a > 0 and b < 0))

2 个答案:

答案 0 :(得分:1)

在第一个if语句中,如果一个为正,一个为负,则立即返回True,甚至不检查negative是否为True。相反,您应该首先检查negative参数(并检查ab均为负),然后检查是否为负或正。

如果a为负,b为正,而negativeTrue,则代码将失败。

答案 1 :(得分:0)

要解释为什么您的代码不等同于解决方案,请参阅调用pos_neg(-1, 1, True)时发生的情况。该解决方案看到负数为true,然后检查a < 0 and b < 0是否同时不小于0,因此返回False。您的代码首先检查它们是否具有不同的符号,因为它们相同,所以返回true。只有当它们具有相同的符号时,您才检查负输入。

相关问题