How to test a variable is null in python

val = ""


del val


if val is None:
print("null")

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

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

366340 次浏览

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

检查 val是否为无:

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

检查名称是否存在:

try:
val
except NameError:
pass  # val does not exist at all
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")

您可以在 try and catch 块中执行以下操作:

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