Check whether a variable is defined or not in Python
The topic deals with the Python variables. Here we are going to determine if a Python variable exists or not.
Certainly, a variable is a container of data. In other words, we can store our data in a variable that we can use for our task.
Defining a Variable :
Data or information needs to be stored for future operations. Moreover, Variable gives the facility to store data.
Let’s see how we define a variable in Python.
a = 4 # a is the variable which stores some data b = 12.9 c = "Hello" # Defining a variable print (a,b,c) # printing the values of the variable
Output : 4 12.9 Hello
Now let’s continue to our topic without wasting any more time…
Check if a variable is defined or not in Python :
A very simple method to check,
Certainly, this is the topic to be dealt with. So let’s see below:
- First of all, if a variable is defined, it would have some data in it.
- If it is not defined then no data is there in it.
The following example will clear the concept regarding this,
a = 4 # a is the variable which stores some data b = 12.9 c = "Hello" # Defining a variable print (c) # c is defined so no error is raised print (d) # d is not defined so error is raised
Output : Hello Traceback (most recent call last): File "main.py", line 10, in <module> print (d) NameError: name 'd' is not defined
So we can see, that there will be an error appear if our variable is not defined.
We can check the existence of a variable using the Python try and except can be used to deal with the following conditions.
- The code is written in the try block.
- If any kind of error arises, then statements in except block get executed.
- If there is no error, except block statements, they are not executed.
The following example may clarify the doubts regarding the use of try/except if any,
a = 10 # a is defined try: print (c) # variable c is not defined. # therefore error raises and control shifts to except block. except: print ("Variable is not defined")
Output : Variable is not defined
Also,read:
This is the way to determine or check whether a variable is defined or not in Python.
a “try: .. except: ” block is pretty expensiv for just checking if a variable is defined, specially if it is checked like this in a loop.
normally you can check it with:
“`python
if ‘c’ in dir():
print (c)
else:
print (“Variable is not defined”)
“`
to check if a variable is in a class dir() or dir().