Boolean Expressions

Cameron Simpson cs at cskk.id.au
Tue Sep 26 18:13:45 EDT 2017


On 26Sep2017 14:43, Cai Gengyang <gengyangcai at gmail.com> wrote:
>Help check if my logic is correct in all 5 expressions

Why not just run some code interactively? Unless this is entirely a thought 
exercise to verify that you have a solid mental understanding of Python 
semantics, all your reasoning is easy to test.

In order to be honest to yourself, you could write does all your answers 
(exactly as you have just done), _then_ go and run the expressions by hand in 
python to see which are correct. You can also run the subparts of the 
expressions, so that you can see which you have misevaluated versus which you 
have made correct/incorrect logic reasoning about.

>A) Set bool_one equal to the result of
>False and False
>
>Entire Expression : False and False gives True because both are False

No. False and anything gives False. An "and" only gives True if both sides are 
true.

>B) Set bool_two equal to the result of
>-(-(-(-2))) == -2 and 4 >= 16 ** 0.5
>
>-(-(-(-2))) is equal to 2, and 2 is not equal to -2, hence the first term       -(-(-(-2))) == -2 is False. 4 >= 16 ** 0.5 is True because 16 ** 0.5 is equal to 4, and 4 is greater then or equal to 4, hence the 2nd term 4 >= 16 ** 0.5 is True.
>
>Entire expression : False because False and True gives False

In python, "and" and "or" short circuit. So if you know enough to evaluate the 
condition from the left hand side, the right hand side is not evaluated at all.

So since 2 == -2 gives False, the expresion is False and the right hand is not 
evaluated.

Note, BTW, that 16 ** 0.5 returns a floating point value. While that particular 
example works nicely, probably because it is all powers of 2 and doesn't hit 
rounding issues, testing equality with floating point is a dangerous area.

>C) Set bool_three equal to the result of
>19 % 4 != 300 / 10 / 10 and False
>
>19 % 4 = 3 which is equal to 300 / 10 / 10 = 3, hence the first term is False. Entire expression is then equal to True, because False and False = True

Entire expression is False because the left hand side is False.

>D) Set bool_four equal to the result of
>-(1 ** 2) < 2 ** 0 and 10 % 10 <= 20 - 10 * 2
>
>-(1 ** 2) is equal to -1 , which is less than 2 ** 0 = 1, hence the first term is True. 2nd term 10 % 10 is equal to 0 , which is less than or equal to 20 - 10 * 2 , hence 2nd term is True.
>
>Entire expression : True and True = True

Correct. (In my head; haven't run the code.)

>E) Set bool_five equal to the result of
>True and True
>
>Entire Expression : True and True = True

Correct.

Cheers,
Cameron Simpson <cs at cskk.id.au>

ERROR 155 - You can't do that.  - Data General S200 Fortran error code list



More information about the Python-list mailing list