Python 'If not' 语法

标签 python python-2.7

我对这么多 Python 开发人员如何/为什么在他们的条件语句中使用 if not 感到有些困惑。

例如,假设我们有一个函数,

def foo(bar = None):
    if not bar:
        bar = 2

但是为什么要这样做呢?我的意思是,不会做 if bar != Noneif bar is not None更明确吗? if not 试图表达什么?

最佳答案

是的,if bar is not None 更明确,因此更好,假设它确实是你想要的。情况并非总是如此,存在细微的差别: if not bar: 将在 bar 是任何类型的零或空容器或 False 时执行>。 许多人确实使用 not bar,而他们确实这样做的意思是 bar is not None

关于Python 'If not' 语法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16739555/

相关文章:

python - BeautifulSoup 在元标签上出错

Python 多处理 EOF

python - numpy 对数组段上的最大值进行向量化

python - QSlider 具有 "arbitrary"值(来自列表/数组)?

Python 数据框 : Get alternative days based on month?

python - 使用串行端口进行多处理

python - 如何确保 buildout 不使用已经安装的包?

python - 如何合并大多数重复的行

Python:将方法作为函数参数传递时出现属性错误

python - 如何在 matplotlib 2.0 中填充只有影线(无背景色)的区域