为什么是'==真不假'在Python语法错误? [英] Why is 'True == not False' a syntax error in Python?

查看:187
本文介绍了为什么是'==真不假'在Python语法错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

== 工作在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
>>> 

为什么这是一个语法错误?我希望不存在虚假是一个前pression返回一个布尔值,真==&LT; X&GT; 是有效的语法,无论&LT; X方式&gt; 是一个前pression与有效的语法

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.

推荐答案

它拥有的在Python 运营商precedence(跨preTER认为你比较真实不,因为 == 具有更高的precedence比不是)。你需要一些括号澄清操作顺序:

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.

这篇关于为什么是'==真不假'在Python语法错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆