如何在python中测试变量为null

Zep*_*Guo 32 python

val = ""

del val

if val is None:
    print("null")
Run Code Online (Sandbox Code Playgroud)

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

如何判断变量是否为null,并避免NameError?

Łuk*_*ski 51

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

检查是否val为None:

if val is None:
    pass  # val exists and is None
Run Code Online (Sandbox Code Playgroud)

要检查名称是否存在:

try:
    val
except NameError:
    pass  # val does not exist at all
Run Code Online (Sandbox Code Playgroud)


Lud*_*sed 6

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")
Run Code Online (Sandbox Code Playgroud)


cez*_*zar 5

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

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