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.
Example:
Examples: Checking local variable existence
def func(): # defining local variable a_variable = 0 # using locals() function # for checking existence in symbol table is_local_var = "a_variable" in locals() # printing result print(is_local_var) # driver code func() |
Output:
True
To check the existence of variable globally we are going to use globals() function to get the dictionary of current global symbol table.
Example:
Examples: Checking global variable existence
def func(): # defining variable a_variable = 0 # using globals() function check # if global variable exist is_global_var = "a_variable" in globals() # printing result print(is_global_var) # driver code func() |
Output:
False
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.
Recommended Posts:
- Python | Check if a variable is string
- Python | Check if variable is tuple
- Check if element exists in list in Python
- Python | Check whether given key already exists in a dictionary
- Python | Check if element exists in list of lists
- Python | Check if a list exists in given list of lists
- Python | Check if tuple exists as dictionary key
- Python - Check if a file or directory exists
- Python: Check if a File or Directory Exists
- Check if a value exists in a DataFrame using in & not in operator in Python-Pandas
- Python | Set 6 (Command Line and Variable Arguments)
- Different ways to access Instance Variable in Python
- Python | Using variable outside and inside the class and method
- Python | Variable list slicing
- Python | Convert 1D list to 2D list of variable length
- Python | setting and retrieving values of Tkinter variable
- Python | Accessing variable value from code scope
- Protected variable in Python
- __file__ (A Special variable) in Python
- Python - Variable Operations Dictionary update
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.

