Skip to content
Related Articles

Related Articles

How to check if a Python variable exists?
  • Last Updated : 29 Dec, 2020

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.

My Personal Notes arrow_drop_up
Recommended Articles
Page :