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)
Don't miss your chance to ride the wave of the data revolution! Every industry is scaling new heights by tapping into the power of data. Sharpen your skills and become a part of the hottest trend in the 21st century.
Dive into the future of technology - explore the Complete Machine Learning and Data Science Program by GeeksforGeeks and stay ahead of the curve.
Last Updated :
22 Mar, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...