Reputation: 8315
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?
Upvotes: 4
Views: 4099
Reputation: 7906
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")
Upvotes: 0
Reputation: 7555
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
Upvotes: 9
Reputation: 6805
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.")
Upvotes: 6
Reputation: 121987
I would suggest:
if condition1:
action1()
if condition2:
action2()
...
if not any(condition1, condition2, ...):
print(...)
Upvotes: 10