zoukankan      html  css  js  c++  java
  • Python内置类型(2)——布尔运算

     

    python中bool运算符按优先级顺序分别有orandnot, 其中orand为短路运算符

    not先对表达式进行真值测试后再取反

    not运算符值只有1个表达式,not先对表达式进行真值测试后再取反,返回的结果不是True就是False

    >>> expression1 = ''
    >>> expression2 = '1'
    >>> not expression1
    True
    >>> not expression2
    False
    

    orand运算符返回的结果是操作符两边的表达式中的符合逻辑条件的其中一个表达式的结果

    在其它语言中,比如C#,bool运算的结果肯定也是bool值;但是python中不是这样的,它返回的是满足bool运算条件的其中一个表达式的值。

    • x or y

    xTrue,则结果为x;若xFalse, 则结果为y

    >>> expression1 = '1'
    >>> expression2 = '2'
    >>> expression1 or expression2
    '1'
    >>> expression2 or expression1
    '2'
    
    • x and y

    xFalse,则结果为x;若xTrue, 则结果为y

    >>> expression1 = ''
    >>> expression2 = {}
    >>> expression1 and expression2
    ''
    >>> expression2 and expression1
    {}
    

    orand运算符是短路运算符

    短路运算符的意思是,运算符左右的表达式的只有在需要求值的时候才进行求值。比如说x or y,python从左到右进行求值,先对表达式x的进行真值测试,如果表达式x是真值,根据or运算符的特性,不管y表达式的bool结果是什么,运算符的结果都是表达式x,所以表达式y不会进行求值。这种行为被称之为短路特性

    #函数功能判断一个数字是否是偶数
    def is_even(num):
        print('input num is :',num)
        return num % 2 == 0
    
    #is_even(1)被短路,不会执行
    >>> is_even(2) or is_even(1)
    input num is : 2
    True
    
    >>> is_even(1) or is_even(2)
    input num is : 1
    input num is : 2
    True
    

    orand运算符可以多个组合使用,使用的时候将以此从左到右进行短路求值,最后输入结果

    表达式x or y and z,会先对x or y进行求值,然后求值的结果再和z进行求值,求值过程中依然遵循短路原则。

    #is_even(2)、is_even(4)均被短路
    >>> is_even(1) and is_even(2) and is_even(4)
    this num is : 1
    False
    
    # is_even(1)为False,is_even(3)被短路
    # is_even(1) and is_even(3)为False,is_even(5)需要求值
    # is_even(1) and is_even(3) or is_even(5)为False,is_even(7)被短路
    >>> is_even(1) and is_even(3) or is_even(5) and is_even(7)
    this num is : 1
    this num is : 5
    False
    

    not运算符的优先级比orand高,一起使用的时候,会先计算not,再计算orand的值

    >>> is_even(1) or is_even(3)
    this num is : 1
    this num is : 3
    False
    >>> not is_even(1) or is_even(3)
    this num is : 1
    True
    >>> is_even(1) or not is_even(3)
    this num is : 1
    this num is : 3
    True
    >>>
    

    not运算符的优先级比==!=低,not a == b 会被解释为 not (a == b), 但是a == not b 会提示语法错误。

    >>> not 1 == 1
    False
    >>> 1 == not 1
    SyntaxError: invalid syntax
    >>> not 1 != 1
    True
    >>> 1 != not 1
    SyntaxError: invalid syntax
    
  • 相关阅读:
    计算机网络 实验之 面向连接和无连接的套接字到底有什么区别?
    计算机网络 实验之 Internet 套接字
    计算机网络 实验之 socket是什么?套接字是什么?
    PepperLa's Boast(单调队列优化二维dp)
    理想的正方形(单调队列在二维的应用)
    移相器以及相控阵雷达移相器位数的选择
    盲速和频闪——雷达
    多普勒效应----雷达
    线性调频(LFM)脉冲压缩-----------雷达
    雷达----脉冲压缩
  • 原文地址:https://www.cnblogs.com/sesshoumaru/p/python-boolean-operations.html
Copyright © 2011-2022 走看看