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.
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.
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.
Python's equivalent of && (logical-and) in an if-statement.
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 evaluatesx
; ifx
isfalse
, its value is returned; otherwise,y
is evaluated and the resulting value is returned.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With