I'm trying to check if a list has no member as boolean operator AND, OR, NOT.
I use:
while ('AND' and 'OR' and 'NOT') not in list:
print 'No boolean operator'
However, when my input is: a1 c2 OR c3 AND
, it prints 'No boolean operator', which means this list is considered no boolean operator in it by using above loop sentence.
Hope somebody can help to correct.
Thanks, Cindy
There is little difference, other than bad style. and if while not pair: did not work, then you have probably been assigning other values to it that are truthy but are not equal to False . If pair is a boolean, and you want to continue while pair is false then while not pair should work.
A WhileNotDoneLoop is a while loop in which the loop-control variable is a boolean, typically named done, which is set to true somewhere in the body of the loop. This is a CodeSmell that may indicate the designer didn't understand the purpose of the loop or didn't understand what the exit condition is.
While loop with else Same as with for loops, while loops can also have an optional else block. The else part is executed if the condition in the while loop evaluates to False . The while loop can be terminated with a break statement. In such cases, the else part is ignored.
The expression 'AND' and 'OR' and 'NOT'
always evaluates to 'NOT'
, so you are effectively doing
while 'NOT' not in some_list:
print 'No boolean operator'
You can either check separately for all of them
while ('AND' not in some_list and
'OR' not in some_list and
'NOT' not in some_list):
# whatever
or use sets
s = set(["AND", "OR", "NOT"])
while not s.intersection(some_list):
# whatever
Using sets
will be screaming fast if you have any volume of data
If you are willing to use sets, you have the isdisjoint()
method which will check to see if the intersection between your operator list and your other list is empty.
MyOper = set(['AND', 'OR', 'NOT'])
MyList = set(['c1', 'c2', 'NOT', 'c3'])
while not MyList.isdisjoint(MyOper):
print "No boolean Operator"
http://docs.python.org/library/stdtypes.html#set.isdisjoint
and
ing strings does not do what you think it does - use any to check if any of the strings are in the list:
while not any(word in list_of_words for word in ['AND', 'OR', 'NOT']):
print 'No boolean'
Also, if you want a simple check, an if
might be better suited than a while
...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With