I'm a little confused with the results I'm getting with the logical operators in Python. I'm a beginner and studying with the use of a few books, but they don't explain in as much detail as I'd like.
here is my own code:
five = 5
two = 2
print five and two
>> 2
It seems to be just outputting the two variable.
five = 5
two = 2
zero = 0
print five and two and zero
So, I added another variable integer. Then I printed and got the following output:
>> 0
What is going on with Python in the background? Why isn't the output something like 7 or 5, 2.
print five and zero and two
--- you would have gotten0
as the result. You could say thatand
"returns the first falsey value it finds, and if it doesn't find anything, returns the last result. - Justin L.and
answers the question: "Are all of these things truthy?", and returns something truthy/falsey as its answer. Considera and b
.and
would checka
first. Ifa
is falsey, then the entireand
statement must return false (because if one thing is false, then it is impossible that both are true). Soand
would return something falsey, and it usesa
(becausea
is already falsey) as a matter of convenience. However, ifa
is true, thenand
needs to only returnb
. - Justin L.b
is truthy, then botha
andb
are truthy. Ifb
is fasley, then it must be that the entireand
statement is false (because not both are true). So the entire result of theand
statement replies completely onb
. Ifb
is true, it gives the right answer. Ifb
is false, it gives the right answer. Soand
will return the first value if the first value is false, and otherwise, return the second value. - Justin L.