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():
a_variable = 0
if 'a_variable' in locals ():
return True
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
a_variable = 0
def func():
if 'a_variable' in globals ():
return True
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
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)
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
22 Mar, 2023
Like Article
Save Article