Why is 'True == not False' a syntax error in Python?

前端 未结 3 1229
难免孤独
难免孤独 2020-12-03 09:33

Comparing boolean values with == works in Python. But when I apply the boolean not operator, the result is a syntax error:

Python 2         


        
相关标签:
3条回答
  • 2020-12-03 10:05

    It's just a matter of operator precedence. Try:

    >>> True == (not False)
    True
    

    Have a look in this table of operator precedences, you'll find that == binds tigher than not, and thus True == not False is parsed as (True == not) False which is clearly an error.

    0 讨论(0)
  • 2020-12-03 10:13

    It has to do with operator precedence in Python (the interpreter thinks you're comparing True to not, since == has a higher precedence than not). You need some parentheses to clarify the order of operations:

    True == (not False)
    

    In general, you can't use not on the right side of a comparison without parentheses. However, I can't think of a situation in which you'd ever need to use a not on the right side of a comparison.

    0 讨论(0)
  • 2020-12-03 10:14

    I think what you are looking for is "and not". This gives you the results you are looking towards. If your comparing booleans what you have is a compound boolean expression, here is an example website Compound Boolean Expression.

    >>> True and True
    True
    >>> True and not True
    False
    >>> True and not False
    True
    >>> False and not True
    False
    >>> False and not False
    False
    >>> False and False
    False
    
    0 讨论(0)
提交回复
热议问题