The Wayback Machine - https://web.archive.org/web/20240717024730/https://www.geeksforgeeks.org/how-to-check-if-a-python-variable-exists/
Open In App

How to check if a Python variable exists?

Last Updated : 02 Jul, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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. 

Python
def func():

  # defining local variable
    a_variable = 0

  # for checking existence in locals() function
    if 'a_variable' in locals():
        return True

# driver code
print(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. 

Python
# defining local variable
a_variable = 0

def func():  

  # for checking existence in globals() function
    if 'a_variable' in globals():
        return True

# driver code
print(func())

Output
True

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

Python
# a_variable = 0

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.

Python
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)

How to check if a Python variable exists? – FAQs

How to check if a variable has any value in Python?

To check if a variable has any value (i.e., it is not None and not an empty value like 0, "", [], etc.), you can use an if statement. Here’s an example:

var = "Hello"

if var:
print("The variable has a value.")
else:
print("The variable is empty or None.")

How to check if a variable has been defined in Python?

To check if a variable has been defined, you can use a try and except block:

try:
var
except NameError:
print("The variable is not defined.")
else:
print("The variable is defined.")

How to check if a variable is None in Python?

To check if a variable is None, you can use the is operator:

var = None

if var is None:
print("The variable is None.")
else:
print("The variable is not None.")

How to use if variable in Python?

Using if variable in Python allows you to check if a variable evaluates to True (i.e., it has a truthy value). For example:

var = [1, 2, 3]

if var:
print("The variable has a truthy value.")
else:
print("The variable is empty or falsy.")

How to check variable type in Python?

To check the type of a variable, you can use the type() function:

var = 42

print(type(var)) # Output: <class 'int'>

if isinstance(var, int):
print("The variable is an integer.")
else:
print("The variable is not an integer.")

Previous Article
Next Article

Similar Reads

Python: Check if a File or Directory Exists
Sometimes the need to check if the folder exists in python, and check whether a directory or file exists becomes important because maybe you want to prevent overwriting the already existing file, or maybe you want to make sure that the file is available or not before loading it. So to check how to check if a Directory Exists without exceptions in P
5 min read
Check if a value exists in a DataFrame using in &amp; not in operator in Python-Pandas
In this article, Let’s discuss how to check if a given value exists in the dataframe or not.Method 1 : Use in operator to check if an element exists in dataframe. C/C++ Code # import pandas library import pandas as pd # dictionary with list object in values details = { 'Name' : ['Ankit', 'Aishwarya', 'Shaurya', 'Shivangi', 'Priya', 'Swapnil'], 'Age
3 min read
Check if Table Exists in SQLite using Python
In this article, we will discuss how to check if a table exists in an SQLite database using the sqlite3 module of Python. In an SQLite database, the names of all the tables are enlisted in the sqlite_master table. So in order to check if a table exists or not we need to check that if the name of the particular table is in the sqlite_master table or
2 min read
Check if a string exists in a PDF file in Python
In this article, we'll learn how to use Python to determine whether a string is present in a PDF file. In Python, strings are essential for Projects, applications software, etc. Most of the time, we have to determine whether a string is present in a PDF file or not. Here, we'll discuss how to check f a string exists in a PDF file in Python. Here, w
2 min read
Check if a Given Key Already Exists in a Python Dictionary
Python dictionary can not contain duplicate keys so it is very crucial to check if a key is already present in the dictionary. If you accidentally assign a duplicate key value, the new value will overwrite the old one. So in a given dictionary, our task is to check if the given key already exists in a dictionary or not. If present, print "present"
5 min read
Python - How to Check if a file or directory exists
Sometimes it's necessary to verify whether a dictionary or file exists. This is because you might want to make sure the file is available before loading it, or you might want to prevent overwriting an already-existing file. In this tutorial, we will cover an important concept of file handling in Python about How to check if a file already exists in
5 min read
Check if element exists in list in Python
The list is an important container in Python as it stores elements of all the data types as a collection. Knowledge of certain list operations is necessary for day-day programming. This article discusses the Fastest way to check if a value exists in a list or not using Python. Example Input: test_list = [1, 6, 3, 5, 3, 4] 3 # Check if 3 exist or no
10 min read
Check if a substring exists having only 2 distinct characters with frequency of one as twice the others
Given a string str[] of N lower case English alphabets, the task is to check if there exists a substring of the given string such that the substring is composed of only two characters and the frequency of 1st character = 2 * frequency of 2nd character. Example: Input: str[] = "aaaabbc"Output: YesExplanation: The substring str[0... 5] = "aaaabb" of
6 min read
How to check whether a file exists without exceptions?
When working with files in Python, it’s often necessary to check if a file exists before attempting to read from or write to it. While exception handling using try and except blocks is a common approach, Python provides cleaner and more intuitive methods to achieve this. In this article, we will explore various ways to check for file existence with
2 min read
Python | Set 6 (Command Line and Variable Arguments)
Previous Python Articles (Set 1 | Set 2 | Set 3 | Set 4 | Set 5) This article is focused on command line arguments as well as variable arguments (args and kwargs) for the functions in python. Command Line Arguments Till now, we have taken input in python using raw_input() or input() [for integers]. There is another method that uses command line arg
2 min read
Practice Tags :
three90RightbarBannerImg