2014-06-30 200 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")