Skip to main content
 首页 » 编程设计

python之使用多个 bool 运算符在 if 语句中抛出 SyntaxError

2025年05月04日14emanlee

这是我的代码:

if mode not "w" or mode not "r+": 
    # do stuff 

这会导致以下错误:

语法错误:语法无效

有人知道我做错了什么吗?

请您参考如下方法:

not不是比较运算符;它是一个一元 bool 运算符,这意味着它只需要一个参数。

也许你想要!= , 不等于?

if mode != "w" and mode != "r+": 

我也替换了or与 and ,因为如果模式等于 'w'它也不等于'r+' .所有这些底片都让人难以理解,你可以使用:

if not (mode == 'w' or mode == 'r+'): 

如果从逻辑上讲更容易理解的话。

您还可以通过使用元组和负成员测试将测试合二为一,not in :

if mode not in ('w', 'r+'): 

这样更容易阅读和理解。