[python] 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?

This question is related to python

The answer is


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")

You can do this in a try and catch block:

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