【问题标题】:Python- Return true if all statements are truePython-如果所有语句都为真则返回真
【发布时间】:2022-11-25 02:07:50
【问题描述】:

我有一个方法,如果所有 3 个语句都为真,我希望它返回真。如果其中任何一个为假,该方法应返回假。

def check_valid(self, a, b):
  
        statement1 = self.x == 0
        statement2 = self.y == a
        statment3 = self.z = b
        return statement1 ^ statement2 ^ statement3

我正在使用 xor 来验证所有语句是否具有相同的值,但如果所有语句都为假,则该方法将返回 true,这不是预期的行为。

为了解决这个问题,我正在考虑像这样向 return 语句添加一个 true :

return true ^ statement1 ^ statement2 ^ statement3

但我认为这不是最好的方法。 有没有更清洁/更好的方法来做到这一点?

【问题讨论】:

  • 你是想写statement3 = self.z == b吗?
  • 我想你要找的是return all([statement1, statement2, statement3])
  • 你也可以使用statement1 and statement2 and statement3

标签: python boolean boolean-logic xor boolean-operations


【解决方案1】:

这种方式将是一种更好的方法并且更具可读性:

def check_valid(self, a, b):
    if not self.x == 0: return False
    if not self.y == a: return False
    if not self.z == b: return False
    return True

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-10-12
    • 1970-01-01
    • 2021-10-15
    • 2016-05-03
    • 2020-03-08
    • 2013-05-15
    • 2013-09-12
    • 2018-07-29
    相关资源
    最近更新 更多