简体   繁体   中英

How could an “also if” be implemented in Python?

I want to implement something conceptually like the following:

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

What would be a reasonable and clear way of implementing logic like this? How could an else be bound to multiple if statements? Would I be forced to create a boolean to keep track of things?

I would suggest:

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

Okay, based on the clarification, something like this would work well:

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"

You can extend this to get other information about the execution of your if statements:

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

You could do something like this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM