Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
511 views
in Technique[技术] by (71.8m points)

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

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

Python 2.7 (r27:82500, Sep 16 2010, 18:02:00) 
[GCC 4.5.1 20100907 (Red Hat 4.5.1-3)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> True == True
True
>>> False == False
True
>>> True is not False
True
>>> True == not False
  File "<stdin>", line 1
    True == not False
              ^
SyntaxError: invalid syntax
>>> 

Why is this a syntax error? I would expect not False to be an expression that returns a boolean value, and True == <x> to be valid syntax wherever <x> is an expression with valid syntax.

question from:https://stackoverflow.com/questions/6100305/why-is-true-not-false-a-syntax-error-in-python

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...