逻辑运算符返回值

301 阅读1分钟

OR运算符

def mod_maker():
    """Return a two-argument function that performs the modulo operation and returns True if the numbers are divisble, and the remainder otherwise.

    >>> mod = mod_maker()
    >>> mod(7, 2) # 7 % 2
    1
    >>> mod(4, 8) # 4 % 8
    4
    >>> mod(8,4) # 8 % 4
    True
    """
    return lambda x,y: x % y or True
>>> 7 and 5
5
>>> 7 and False
False
>>> 7 or 5
7
>>> 7 or False
7
>>> False or 7
7
>>> 0 or True
True

如果x%y=0那么为假值,输出True

如果不为0,直接输出

使用 and 时,从左到右 进行逻辑运算 (判定输出结果)。一旦遇到 bool 逻辑为 False 的值,则 立刻返回该值 且不再往后运算;否则,所有元素的 bool 逻辑值均为 True,and 将返回 最后一个值

使用 or 时,从左到右 进行逻辑运算 (判定输出结果)。一旦遇到 bool 逻辑为 True 的值,则 立刻返回该值 ****且不再往后运算;否则,所有元素的 bool 逻辑值均为 False,or 将返回 最后一个值

Boolean operators. Three basic logical operators are also built into Python:

>>> True and False
False
>>> True or False
True
>>> not False
True

Logical expressions have corresponding evaluation procedures. These procedures exploit the fact that the truth value of a logical expression can sometimes be determined without evaluating all of its subexpressions, a feature called short-circuiting.

To evaluate the expression <left> and <right>:

  1. Evaluate the subexpression <left>.
  2. If the result is a false value v, then the expression evaluates to v.
  3. Otherwise, the expression evaluates to the value of the subexpression <right>.

To evaluate the expression <left> or <right>:

  1. Evaluate the subexpression <left>.
  2. If the result is a true value v, then the expression evaluates to v.
  3. Otherwise, the expression evaluates to the value of the subexpression <right>.

To evaluate the expression not <exp>:

  1. Evaluate <exp>; The value is True if the result is a false value, and False otherwise.

These values, rules, and operators provide us with a way to combine the results of comparisons. Functions that perform comparisons and return boolean values typically begin with is, not followed by an underscore (e.g., isfiniteisdigitisinstance, etc.).