Boolean Operator Confusion

Terry Reedy tjreedy at
Sat Apr 25 02:51:04 CEST 2015

On 4/24/2015 10:50 AM, subhabrata.banerji at wrote:
> Dear Group,
> I am trying to understand the use of Boolean operator in Python. I am trying to
> write small piece of script, as follows,
> def input_test():
> 	str1=raw_input("PRINT QUERY:")
> 	if "AND" or "OR" or "NOT" in str1:
> 		print "It is a Boolean Query"
> 	elif "AND" or "OR" or "NOT" not in str1:
> 		print "It is not a Boolean Query"
> 	else:
> 		print "None"

 > I am trying to achieve if the words "AND","OR","NOT" ... in string I 
want to recognize it as,
 > Boolean Query, if they are not there the string is not Boolean query.
 > As I am trying to test it I am getting following output,
 >>>> input_test()
 > PRINT QUERY:obama AND clinton
 > It is a Boolean Query

 >>>> input_test()
 > PRINT QUERY:obama clinton
 > It is a Boolean Query

Functions that do real calculation should be written as functions that 
take an input object (or objects) and produce an output object.  You can 
then write automated tests can be run repeatedly.

Retyping the function name (multiple times) and test strings every time 
you modify and retest the function is tedious and *subject to error*. 
It is easy to write simple test functions.  Example implementing both ideas:

def is_bool_text(text):
     if "AND" or "OR" or "NOT" in text:
         return True
     elif "AND" or "OR" or "NOT" not in text:
         return False

def test_is_bool_text():
     for inp, expect in (('obama AND clinton', True),
                         ('obama clinton', False),
         print(inp, 'PASS' if is_bool_text(inp) == expect else 'FAIL')


Currently, the second example is FAIL.  You can now modify the function 
and re-run the test until both examples PASS.  Then add more test cases.

Based on my experience reading newbie posts on python list and 
Stackoverflow, learning to write real functions, without input and 
print, and repeatable tests, is the most important thing many people are 
not learning from programming books and classes.

Terry Jan Reedy

More information about the Python-list mailing list