如果"也是如何"用Python实现?

时间:2014-06-30 16:18:56

标签: python if-statement series

我想在概念上实现以下内容:

if condition1:
    action1()
also if condition2:
    action2()
also if condition3:
    action3()
also if condition4:
    action4()
also if condition5:
    action5()
also if condition6:
    action6()
else:
    print("None of the conditions was met.")

这样实现逻辑的合理而明确的方法是什么?如何将else绑定到多个if语句?我是否会被迫创建一个布尔来跟踪事物?

4 个答案:

答案 0 :(得分:10)

我建议:

if condition1:
    action1()
if condition2:
    action2()
...
if not any(condition1, condition2, ...):
    print(...)

答案 1 :(得分:9)

好的,基于澄清,这样的事情会很好:

class Accumulator(object):
    none = None
    def also(self, condition):
        self.none = not condition and (self.none is None or self.none)
        return condition

acc = Accumulator()
also = acc.also

if also(condition1):
    action1()
if also(condition2):
    action2()
if also(condition3):
    action3()
if also(condition4):
    action4()
if acc.none:
    print "none passed"

您可以对此进行扩展以获取有关if语句执行的其他信息:

class Accumulator(object):
    all = True
    any = False
    none = None
    total = 0
    passed = 0
    failed = 0

    def also(self, condition):
        self.all = self.all and condition
        self.any = self.any or condition
        self.none = not condition and (self.none is None or self.none)
        self.total += 1
        self.passed += 1 if condition else self.failed += 1 
        return condition

答案 2 :(得分:7)

conditionMet = False
if condition1:
    action1()
    conditionMet = True
if condition2:
    action2()
    conditionMet = True
if condition3:
    action3()
    conditionMet = True
if condition4:
    action4()
    conditionMet = True
if condition5:
    action5()
    conditionMet = True
if condition6:
    action6()
    conditionMet = True

if not conditionMet:
    print("None of the conditions was met.")

答案 3 :(得分:0)

你可以这样做:

conditions = [condition1,condition2,condition3,condition4,condition5,condition6]
actions = [action1, action2, action3, action4, action5, action6]

for condition, action in zip(conditions, actions):
    if condition:
        action()

if not any(conditions):
    print("None of the contitions was met")