Comp Sci: Python: checking if a variable exists

Self-tutoring about Python: the tutor mentions a favourite test of his.

In any programming language, I like to discover how to test the existence of a variable. It’s more straightforward in some than others.

Python really shines in this regard, with its great way of handling exceptions. First of all, it’s important to realize that when a variable is mentioned that doesn’t exist, Python gives a NameError exception. In the repl, I entered the following:

del var1 # make sure var1 not defined
try:
print(‘var1 is’,var1)
except NameError:
print(‘var1 not defined’)

Python’s exception handling mechanism is really convenient: it can steer you around the quicksand of “not defined”, etc

Source:

stackoverflow.com: paxdiablo’s answer

Jack of Oracle Tutoring by Jack and Diane, Campbell River, BC.

Leave a Reply