Skip to content
Related Articles

Related Articles

How to check if a Python variable exists?

View Discussion
Improve Article
Save Article
  • Last Updated : 18 Jul, 2022
View Discussion
Improve Article
Save Article

Variables in Python can be defined locally or globally. There are two types of variables first one is a local variable that is defined inside the function and the second one are global variable that is defined outside the function. 

Method 1: Checking the existence of a local variable

To check the existence of variables locally we are going to use the locals() function to get the dictionary of the current local symbol table. 

Python3




def func():
 
  # defining local variable
    a_variable = 0
 
  # for checking existence in locals() function
    if 'a_variable' in locals():
        return True
 
# driver code
func()

Output:

True

Method 2: Checking the existence of a globel variable

To check the existence of variables globally we are going to use the globals() function to get the dictionary of the current global symbol table. 

Python3




# defining local variable
a_variable = 0
 
def func(): 
 
  # for checking existence in globals() function
    if 'a_variable' in globals():
        return True
 
# driver code
func()

Output:

False

Method 3: Testing if a Variable Is Defined or not using try and except

A NameError exception is raised when attempting to access a variable that hasn’t yet been defined, you can manage this with a try/except statement

Python3




# a_variable = 0
 
try:
    a_variable
    print("Yes")
except NameError:
    print("Error: No value detected")

Output:

Error: No value detected

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!