How to check if a Python variable exists?
Variables in Python can be defined locally or globally. There are two types of variable first one is local variable that is defined inside the function and the second one are global variable that is defined outside the function.
To check the existence of variable locally we are going to use locals() function to get the dictionary of current local symbol table.
Examples: Checking local variable existence
To check the existence of variable globally we are going to use globals() function to get the dictionary of current global symbol table.
Examples: Checking global variable existence
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course