Check if a variable exists or not in Python
When coding or practicing some problems, you declare variables in your code. Variables are like containers that are used to store information. Variables can be defined globally (defined outside the function) and locally (defined inside the function). In this post, we will see if a variable exists in Python. Now, some variables in programming languages are defined already and you can’t overwrite those variables, they are known as pre-defined variables. Alternatively, some variables are user-defined, which a user defines while writing the code. Let’s move forward and learn some ways to know if a variable exists or not in Python.
Method 1: try block to check if a variable is declared or not in Python
We will use, try, and
except statements. These statements first attempt a method written in the try block and if that method doesn’t work, they implement what is written on the except block. They are generally used for error checking.
NameError: arises when we try accessing a variable in our program that already exists.
variable = 0 #defining a varibale in python try: variable # trying to see if the varibale exists print("Yes") except NameError: # NameError exception is arises when we attempt #to access a variable that hasn’t yet been defined. print("Error: No value detected")
Method 2: Using If statement and locals()
Using if statement and checking in locals().
def function(): # defining a local variable variable = 0 # for checking existence in locals() function if 'variable' in locals(): return True # calling the function function()
Method 3: using globals()
Using if statements and checking in globals().
# defining a local variable variable = 0 def function(): # for checking existence in globals() function if 'variable' in globals(): return True # calling the function function()
With this third method, we have completed our tutorial on checking if a variable exists in Python or not.
Do you now want to learn how we Set environmental variables in Python? Follow this link Set environmental variables in Python