Boolean Expressions

Thomas Jollans tjol at tjol.eu
Tue Sep 26 18:43:28 EDT 2017


On 27/09/17 00:23, Cai Gengyang wrote:
> I'm trying to understand the logic behind AND. I looked up Python logic tables
>
> False and False gives False
> False and True gives False
> True and False gives False
> True and True gives True.
>
> So does that mean that the way 'and' works in Python is that both terms must be True (1) for the entire expression to be True ? Why is it defined that way, weird ? I was always under the impression that 'and' means that when you have both terms the same, ie either True and True or False and False , then it gives True 

What gave you that impression? This is the way "and" is defined in
formal logic, electronics, programming, and all languages that I know.

no and no does not mean  yes.

(There may be ambiguity in what precisely "or" means in English, but
"and" is pretty clear...)

The logical operation you're thinking of is sometimes called "XNOR". One
way to write this in Python is bool(a) == bool(b)

Python 3.5.3 (default, Jan 19 2017, 14:11:04)
[GCC 6.3.0 20170118] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> def xnor(a, b):
...     return bool(a) == bool(b)
...
>>> xnor(True, True)
True
>>> xnor(True, False)
False
>>> xnor(False, False)
True
>>> xnor(False, True)
False
>>>



>
>
>
>
>
> On Wednesday, September 27, 2017 at 5:54:32 AM UTC+8, Chris Angelico wrote:
>> On Wed, Sep 27, 2017 at 7:43 AM, Cai Gengyang <gengyangcai at gmail.com> wrote:
>>> Help check if my logic is correct in all 5 expressions
>>>
>>>
>>> A) Set bool_one equal to the result of
>>> False and False
>>>
>>> Entire Expression : False and False gives True because both are False
>> This is not correct, and comes from a confusion in the English
>> language. In boolean logic, "and" means "both". For instance:
>>
>> *IF* we have eggs, *AND* we have bacon, *THEN* bake a pie.
>>
>> Can you bake an egg-and-bacon pie? You need *both* ingredients. The
>> assertion "we have eggs" is True if we do and False if we do not; and
>> the overall condition cannot be True unless *both* assertions are
>> True.
>>
>> In Python, the second half won't even be looked at if the first half
>> is false. That is to say, Python looks beside the stove to see if
>> there's a carton of eggs, and if it can't see one, it won't bother
>> looking in the freezer for bacon - it already knows we can't bake that
>> pie.
>>
>> Your other questions are derived from this one, so you should be fine
>> once you grok this one concept.
>>
>> ChrisA





More information about the Python-list mailing list