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 gotten0as the result. You could say thatand"returns the first falsey value it finds, and if it doesn't find anything, returns the last result.andanswers the question: "Are all of these things truthy?", and returns something truthy/falsey as its answer. Considera and b.andwould checkafirst. Ifais falsey, then the entireandstatement must return false (because if one thing is false, then it is impossible that both are true). Soandwould return something falsey, and it usesa(becauseais already falsey) as a matter of convenience. However, ifais true, thenandneeds to only returnb.bis truthy, then bothaandbare truthy. Ifbis fasley, then it must be that the entireandstatement is false (because not both are true). So the entire result of theandstatement replies completely onb. Ifbis true, it gives the right answer. Ifbis false, it gives the right answer. Soandwill return the first value if the first value is false, and otherwise, return the second value.