Python 检查 NoneType 不起作用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20405628/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python check for NoneType not working
提问by Alex Blundell
I'm trying to check whether an object has a None type before checking it's length. For this, I've done an if statement with an or operator:
在检查对象的长度之前,我试图检查它是否具有 None 类型。为此,我用 or 操作符做了一个 if 语句:
if (cts is None) | (len(cts) == 0):
return
As far as I can tell, the object ctswill be checked if it's None, and if it is, the length check won't run. However, the following error happens if ctsis None:
据我所知,对象cts是否为 None 将被检查,如果是,则不会运行长度检查。但是,如果cts为 None,则会发生以下错误:
TypeError: object of type 'NoneType' has no len()
TypeError: object of type 'NoneType' has no len()
Does python check both expressions in an if statement, even if the first is true?
即使第一个为真,python 是否会检查 if 语句中的两个表达式?
采纳答案by Alex Blundell
In Python, |is a bitwise or. You want to use a logical orhere:
if (cts is None) or (len(cts) == 0):
return
回答by Arovit
You can also use -
您还可以使用 -
if not cts: return

