Boolean Operator Confusion

subhabrata.banerji at gmail.com subhabrata.banerji at gmail.com
Fri Apr 24 18:40:10 CEST 2015


On Friday, April 24, 2015 at 8:45:04 PM UTC+5:30, Steven D'Aprano wrote:
> On Sat, 25 Apr 2015 12:50 am,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"
> 
> First problem: why do you sometimes return "None"? You have two possible
> answers: either something is a boolean query, or it is not. There is no
> third choice. ("It's a boolean query, but only on Wednesdays.")
> 
> So your code you have if...else and no "elif" needed.
> 
>     if <test for boolean query>:
>         print "It is a Boolean Query"
>     else:
>         print "It is not a Boolean Query"
> 
> 
> Now let us look at your test for a boolean query:
> 
>     "AND" or "OR" or "NOT" in str1
> 
> 
> How does a human reader understand that as English?
> 
>     if "AND" is in the string, or "OR" is in the string, or "NOT" 
>     is in the string, then it is a boolean query.
> 
> But sadly, that is not how Python sees it. Python sees it as:
> 
>     if "AND" is a true value, or if "OR" is a true value, 
>     or if "NOT" is in the string, then it is a boolean query.
> 
> "AND" is always a true value. All strings except for the empty string "" are
> true values, so expressions like:
> 
>     if X or Y or Z in some_string
> 
> will always be true, if X or Y are true values.
> 
> You need to re-write your test to be one of these:
> 
>     # version 1
>     if "AND" in str1 or "OR" in str1 or "NOT" in str1:
>         print "It is a Boolean Query"
>     else:
>         print "It is not a Boolean Query"
> 
> 
>     # version 2
>     if any(word in str1 for word in ("AND", "OR", "NOT")):
>         print "It is a Boolean Query"
>     else:
>         print "It is not a Boolean Query"
> 
> 
> 
> 
> -- 
> Steven

Thanks Steven for taking so much of your valuable time to make me understand and nice guidance. Ian your suggestion worked well. Thank you. Regards, Subhabrata Banerjee.



More information about the Python-list mailing list