Python's Logical Operator AND

|▌冷眼眸甩不掉的悲伤 提交于 2019-11-26 11:50:12
tdelaney

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.

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

Boolean And operators will return the first value 5 if the expression evaluated is false, and the second value 2 if the expression evaluated is true. Because 5 and 2 are both real, non-false, and non-null values, the expression is evaluated to true.

If you wanted to print both variables you could concatenate them to a String and print that.

five = 5
two = 2
print five + " and " + two

Or to print their sum you could use

print five + two

This document explains how to use the logical Boolean operators.

This AND in Python is an equivalent of the && in Java for instance. This doesn't mean the and in the English language. The AND is a logical operator. Assume five holds 5 and two holds 2. From Python documentation: 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. Basically, it evaluates the last integer in your case which is true.

if (five and two):
...     print "True"
... else:
...     print "False"

The AND is a logical operator, to test the logic for a specific case, not an arithmetic operator. If you want to get results like 7 for five and two, you should rather use "+" which means adding two integers. See below:

>>> five = 5
>>> two = 2
>>> print five + two
7
bobalukalallu

Try 0 and 9.

The result is 0 because the value of 0 is false. The operand on the left of the and operator is False so the whole expression is False and returns 0

In Python any non-zero integer value is true; zero is false.

The OP’s values are both non-zero.

The AND operator tests from left to right,

with and, if all values are True, returns the last evaluated value. If any value is false, returns the first one.

Since both are non-zero, both are true, so the last value is returned

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!