Mr.Robot
Mr.Robot

Reputation: 349

Writing neat branching conditions

Problem

I have 5 boolean variables is_A through is_E and their combinations correspond to different downstream operations. However, currently I need to write a 32 conditionals that look like

if xxx:
# do something
elif is_A == True & is_B == False & ... & is_E == True:
# do something
...
elif xxx:
# do something
else xxx:
# do something

However, those conditionals look ugly to me and it is quite boring to write those boilerplate.

I am wondering if there is more elegant way to write them?

Upvotes: 0

Views: 48

Answers (1)

Amal K
Amal K

Reputation: 4909

An alternative syntax would be to use the any and all functions. Both of them take an iterable like a list as an argument. any returns True if any of the conditions is True like logical or and all returns True only if all of its values evaluate to True like logical and. Secondly, do not use ==True and ==False

elif all([ is_A, not is_B,..., is_E]):


And in Python, the logical AND operator is and, & is Bitwise AND.

Upvotes: 1

Related Questions