How to check null variable in python

val = "" del val if val is None: print("null") 

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

How to determine if a variable is null and avoid a NameError?

+5
source share
3 answers

Testing a name pointing to None and an existing one are two semantically different operations.

To check for val :

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

To check if a name exists:

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

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 
+2
source

All Articles