如何在python中测试变量是否为空

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/43934304/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 23:32:39  来源:igfitidea点击:

How to test a variable is null in python

python

提问by Zephyr Guo

val = ""

del val

if val is None:
    print("null")

I ran above code, but got NameError: name 'val' is not defined.

我运行了上面的代码,但得到了NameError: name 'val' is not defined.

How to decide whether a variable is null, and avoid NameError?

如何判断一个变量是否为空,避免NameError?

回答by ?ukasz Rogalski

Testing for name pointing to Noneand name existing are two semantically different operations.

测试名称指向None和名称存在是两个语义不同的操作。

To check if valis None:

要检查是否val为 None:

if val is None:
    pass  # val exists and is None

To check if name exists:

要检查名称是否存在:

try:
    val
except NameError:
    pass  # val does not exist at all

回答by Ludisposed

try:
    if val is None: # The variable
        print('It is None')
except NameError:
    print ("This variable is not defined")
else:
    print ("It is defined and has a value")

回答by cezar

You can do this in a try and catch block:

您可以在 try 和 catch 块中执行此操作:

try:
    if val is None:
        print("null")
except NameError:
    # throw an exception or do something else