2014-06-30 59 views
3

我想要实现的东西概念类似如下:如何在Python中实现“如果”?

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语句?我会被迫创建一个布尔值来跟踪事物吗?

+0

这与elif'有什么不同? –

+4

只要删除无效的'也'。如果条件不相关,只需用'if ..:'检查每个条件。 –

+1

@ g.d.d.c但他需要一个'else'来包含'如果没有任何(条件)' –

回答

8

好的基础上,澄清,像这样将工作做好:

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 
+0

这很可爱!我喜欢 –

+0

非常感谢您对此的帮助。 @jonrsharpe描述的[任何方法](http://stackoverflow.com/questions/24494596/how-could-an-also-if-be-implemented-in-python/24494639#24494639)非常好,但需要条件要指定两次。你的方法允许单一的条件说明,并且可以使用类似英语的句法。谢谢! – d3pd

10

我建议:

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

非常感谢您的帮助。我不知道''''''''''功能,从概念上讲,这正是我所需要的。但它确实需要所有条件都要指定两次,这就是为什么我认为@Jamie Cockburn提供的[答案](http://stackoverflow.com/a/24495556/1556092)(其中布尔值用于保持跟踪和条件只指定一次)更有意义。我真诚地感谢你的帮助! – d3pd

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.") 
+1

您的最后一行是混合语言。你的意思是,如果不是conditionMet' –

+2

'conditions = {condition1:action1,condition2:action2,...};条件:action.inms():如果条件:action(); conditionMet = True' –

+0

@AdamSmith这是最干净的场景。 –

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")