Python bool statements [duplicate]

Tags: python boolean
Question!

why would it return 77 in case 3? isn't it a bool statement? Note that case 1 and 2 return False. What is the difference between case 2 and 3?

7 >= 77 and 77 
Out[313]: False

7 >= 77 and 7
Out[314]: False

7 >= 7 and 77
Out[315]: 77

7 >= 8 and 77
Out[318]: False

Thanks

regarding @Kasramvd's comment that my question is the exact duplicate of the question from another user (see below)

it is not obvious at all to me, a novice, that my question is the same as the below. An expert can easily see that the same answer apply to both. After reading answers, i do see a link. Before getting the answers, no way I could've known.

i am a novice in programming. And it was my first time joining stack over flow. And this was my first question on stackoverflow. It appears that stackoverflow is not novice friendly. Thanks for blocking me to ask more questions.Just found that out too.


another user's question

I am trying to understand this code from someone else's project. If you want the context it's here: https://github.com/newsapps/beeswithmachineguns/blob/master/beeswithmachineguns/bees.py#L501

IS_PY2 is just a boolean variable, True if the Python major version is 2. I know that a non-empty string is True, but for some reason I don't understand openmode is assigned either 'w' or 'wt' rather than True or False.

openmode = IS_PY2 and 'w' or 'wt'
openkwargs = IS_PY2 and {} or {'encoding': 'utf-8', 'newline': ''}


Answers

I believe the mechanics of and statements in python work like this.

The conditions in the and statements are evaluated sequentially. If a falsy thing is found, then this is returned as it is. Otherwise, the last thing in the and conditions is returned.

In Python things have the notion of being truthy or falsy without necessarily being boolean variables. Thus, the and just returns either the first thing that is falsy, or the last condition. In this case, it is retuning 77 and if you put this in a conditional, it would be treated as a True because 77 is truthy.

For ex, if you do

7>=7 and False and 77 # ===> False
7>=7 and 0 and 77 # ===> 0
7>=7 and [] and 77 # ===> []

So you see it doesn't return True/False necessarily, it just returns the first falsy thing it sees or returns the last thing.

By : gowrath


This has to do with the fact that and short-circuits, and returns the truthy value instead of True or False.

In:

7 >= 77 and 7

7 >= 77 equates to False, so the second operand of and is never evaluated, so it becomes False.

In:

7 >= 7 and 77

7 is equal to 7 (obviously), so the second operand of and is evaluated. Since 77 is truthy, it's what's returned.



You need a logical condition in the while. Perhaps

program.toUpperCase().equals("Y")
By : nicomp


This video can help you solving your question :)
By: admin