Open Side Menu Go to the Top
Register
Boolean Operator logic question Boolean Operator logic question

08-11-2014 , 12:28 PM
Learning some programming, using Python 2.7

Im baffled by the logic of the operators in these bits of code, if someone could explain how the logic works to me that would be great:

Code:
'a' == ('b' or 'a')
is False

but
Code:
'a' == ('a' or 'b')
is True... intuitively I would have expected both these above to be true.

I also don't understand why
Code:
'a' == ('b' and 'a')
is True,
and if that's True (which I don't get), why then is
Code:
'a' == ('a' and 'b')
False?
Boolean Operator logic question Quote
08-11-2014 , 12:35 PM
Forget about the comparison to 'a' for a second and just look at what the right hand side returns.

Code:
('b' or 'a')
Returns 'b'

Code:
('a' or 'b')
Returns 'a'.

So your first two examples simplify down to:

Code:
'a' == 'b'
'a' == 'a'
In which case it should be clear why the first is False but the second is True.


In a bigger sense, what you're doing is confusing you because you're conflating multiple concepts (boolean logic, short circuiting, and truth-y values).

An 'or' is going to return the first 'True' value it finds because thats all it needs to evaluate. In this case both 'a' and 'b' qualify as True-ish values for Python.

For your 'and' case, every condition is evaluated and so the last of 'a' and 'b' is returned.
Boolean Operator logic question Quote
08-11-2014 , 12:52 PM
what jj said.

if you want to do it the way you are thinking about it in your head, you would write it as:

Code:
'a' == 'b' or 'a' == 'a'
same with AND statement
Code:
'a' == 'a' and 'a' == 'b'

you can also do something like

Code:
'a' in {'b', 'a', 'c'}
which is asking if 'a' is in that set, which is an better way of writing
Code:
 'a' == 'b' or 'a' == 'a' or a == 'c'
if you have a lot of compares to make (you can obviously also do it with less than 3 items in your set, I just used 3 cuz I though it showed the concept better)

Last edited by Alobar; 08-11-2014 at 12:59 PM.
Boolean Operator logic question Quote
08-11-2014 , 01:09 PM
jj, Alobar

Thanks for explaining, makes sense now!
Boolean Operator logic question Quote
08-11-2014 , 03:13 PM
Quote:
Originally Posted by jjshabado
An 'or' is going to return the first 'True' value it finds because thats all it needs to evaluate. In this case both 'a' and 'b' qualify as True-ish values for Python.

Further, this is a language specific feature. You wouldn't be out of line to think that:

Code:
('b' or 'a')
always returns "true" instead of 'b'. Some languages will return true/false while others will return the nonzero true value as in this case, which is then short circuited to the first result
Boolean Operator logic question Quote
08-12-2014 , 06:09 PM
Yeah, not every language works like this.
Boolean Operator logic question Quote

      
m