Skip to content
Related Articles
Get the best out of our app
GeeksforGeeks App
Open App
geeksforgeeks
Browser
Continue

Related Articles

How to check if a Python variable exists?

Improve Article
Save Article
Like Article
Improve Article
Save Article
Like 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 global 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

Using the ‘in’ keyword:

Approach:

You can use the ‘in’ keyword to check if a variable is defined or not.

Python3




if 'my_variable' in locals():
    print('Variable exists')
else:
    print('Variable does not exist')

Output

Variable does not exist

Time complexity: O(1)
Space complexity: O(1)


My Personal Notes arrow_drop_up
Last Updated : 22 Mar, 2023
Like Article
Save Article
Similar Reads
Related Tutorials