Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python's Logical Operator AND

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.

like image 944
BubbleMonster Avatar asked Aug 12 '13 19:08

BubbleMonster


People also ask

Is there an and/or operator in Python?

There are three Boolean operators in Python: and , or , and not . With them, you can test conditions and decide which execution path your programs will take. In this tutorial, you'll learn about the Python or operator and how to use it.

Does Python use && or and?

To use the and operator in Python, use the keyword and instead of && because there is no && operator in Python. If you use && operator in Python, you will get the SyntaxError.

What is the && operator in Python?

Python's equivalent of && (logical-and) in an if-statement.


2 Answers

Python Boolean operators return the last value evaluated, not True/False. The docs have a good explanation of this:

The expression x and y first evaluates x; if x is false, its value is returned; otherwise, y is evaluated and the resulting value is returned.

like image 151
tdelaney Avatar answered Oct 06 '22 21:10

tdelaney


As a bit of a side note: (i don't have enough rep for a comment) The AND operator is not needed for printing multiple variables. You can simply separate variable names with commas such as print five, two instead of print five AND two. You can also use escapes to add variables to a print line such as print "the var five is equal to: %s" %five. More on that here: http://docs.python.org/2/library/re.html#simulating-scanf

Like others have said AND is a logical operator and used to string together multiple conditions, such as

if (five == 5) AND (two == 2):     print five, two 
like image 43
aChipmunk Avatar answered Oct 06 '22 21:10

aChipmunk