如何在python中测试变量为空null

How to test a variable is null in python

本问题已经有最佳答案,请猛点这里访问。
1
2
3
4
5
6
val =""

del val

if val is None:
    print("null")

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

如何判断变量是否为空,避免名称错误?


测试指向None的名称和现有名称是两种语义不同的操作。

检查val是否为无:

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

要检查名称是否存在:

1
2
3
4
try:
    val
except NameError:
    pass  # val does not exist at all

1
2
3
4
5
6
7
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")


您可以在尝试捕获块中执行此操作:

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