How do I check if a variable exists in python

0 votes

I want to check if a variable exists. Now I'm doing something like this:

except NameError:
   # Do something.

Are there other ways without exceptions?

Dec 28, 2020 in Python by anonymous
• 10,480 points

2 answers to this question.

0 votes

Variables in Python can be defined locally or globally. There are two types of the variable 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.

To check the existence of the variable locally we are going to use the locals() function to get the dictionary of the current local symbol table.

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



# driver code



answered Dec 28, 2020 by Gitika
• 65,950 points
0 votes

Python doesn’t have a specific function to test whether a variable is defined, since all variables are expected to have been defined before use, even if initially assigned the None object.

answered Dec 28, 2020 by Carlos

Related Questions In Python

0 votes
1 answer

How do I check if input string is a valid regular expression or not in Python?

Hi. Good question! Well, just like what ...READ MORE

answered Feb 12, 2019 in Python by Nymeria
• 3,520 points
0 votes
1 answer

How do I check if a list is empty in python?

Hey @Vedant, that's pretty simple and straightforward: if ...READ MORE

answered May 28, 2019 in Python by Karthik
0 votes
1 answer

How do I use urllib to see if a website is 404 or 200 in Python?

For Python 3, try doing this: import urllib.request, ...READ MORE

answered Nov 29, 2018 in Python by Nymeria
• 3,520 points

edited Dec 11, 2018 by Nymeria 9,301 views
0 votes
1 answer

how do I check the length of an array in a python program?

lets say we have a list mylist = ...READ MORE

answered Mar 12, 2019 in Python by Mohammad
• 3,230 points
0 votes
2 answers
+1 vote
2 answers

how can i count the items in a list?

Syntax :            list. count(value) Code: colors = ['red', 'green', ...READ MORE

answered Jul 7, 2019 in Python by Neha
• 330 points

edited Jul 8, 2019 by Kalgi 2,411 views
0 votes
0 answers
+5 votes
6 answers

Lowercase in Python

You can simply the built-in function in ...READ MORE

answered Apr 11, 2018 in Python by hemant
• 5,810 points
0 votes
1 answer

How do I check if a given Python string is a substring of another one?

Try using in like this: >>> x = 'hello' >>> y ...READ MORE

answered Nov 26, 2020 in Python by Gitika
• 65,950 points
0 votes
4 answers

How do I remove an element from a list by index in Python?

1886 Use del and specify the index of the element ...READ MORE

answered Dec 11, 2020 in Python by Gitika
• 65,950 points