a='1'
b='Apple'
c='Banana'
d='Some thing'
e=''
f=''
if (a and b and c !='') or (d and e and f !=''):
print("OKAY")
else:
print("Not OKAY")
As of my example code it is printing okay. But it should be print Okay either both d,e and f are should be empty or both should not to be empty. For example if a,b and c are not empty and d,e and f are empty then it should be print “okay”. And a, b, c are not empty and d is not empty, e and f are empty so in this case it should print “not OKAY”. Or if ab and c are not empty and d, e and f are also not empty then it should be print “OKAY”. How to do. I don’t have an practical idea that’s why i could not given an example.
Advertisement
Answer
So your condition is that all items in a group need to be the same, empty or non-empty, and at least one of the two groups needs to be all non-empty. So you could say that each group has a ternary state: True
(all non-empty), False
(all empty) or None
(mixed emptiness):
def group_state(*args):
result = set(map(bool, args))
if len(result) > 1:
return None # mixed truthiness
return result.pop() # one True or False value
Then you would have a comparison like:
if group_state(a, b, c) is not None and group_state(d, e, f) is not None
and (group_state(a, b, c) or group_state(d, e, f)):
Which we can write a little more elegantly as:
try:
result = sum((group_state(a, b, c), group_state(d, e, f))) >= 1
except TypeError:
result = False
if result:
We’re taking advantage of the fact that True
behaves as 1
, False
behaves as 0
, and None
cannot be summed up and results in a TypeError
. So if either group results in None
, it’ll raise a TypeError
and the end result is False
. Otherwise, we’ll want at least one group to be truthy, i.e. the sum
needs to be at least 1
.