• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar

The Programming Expert

Solving All of Your Programming Headaches

  • HTML
  • JavaScript
  • jQuery
  • PHP
  • Python
  • SAS
  • Ruby
  • About
You are here: Home / Python / How to Check if Variable Exists in Python

How to Check if Variable Exists in Python

February 16, 2022 Leave a Comment

Checking if a variable exists in Python is easy. To check if a variable exists, the easiest way is with exception handling.

try:
    print(variable)
except NameError:
    print("variable doesn't exist")

#Output:
variable doesn't exist.

You can use the Python globals() functions to check if a variable exists globally.

variable = "this is a variable"

if 'variable' in globals():
   print("variable exists in global variables!")

#Output:
variable exists in global variables!

Finally, if you want to check if a variable exists locally, you can use the Python locals() function.

def someFunction():
    variable = "this is a variable"
    if 'variable' in locals():
        print("variable exists in local variables!")

someFunction()

#Output:
variable exists in local variables!

When working in Python, one of the worst experiences is when you run a piece of a code and you receive an error because a variable doesn’t exist.

Luckily, we can check if a variable exists in Python easily so we don’t have errors in our code.

Checking for the existence of variable can be done in Python in a few different ways, but the easiest way is with exception handling.

In a try block, we can try and use the variable. If the variable doesn’t exist, then a NameError will be raised and we can handle the error in the except block.

Below is how to check if a variable exists in Python with exception handling.

try:
    print(variable)
except NameError:
    print("variable doesn't exist")

#Output:
variable doesn't exist.

If instead, you are trying to check for the existence of an attribute in an object, you can check if an attribute exists in an object with the hasAttr() function.

Using Python to Check if Variable Exists Globally

In many programming languages, the concept of scope is very important and affects how the flow of data occurs in a program. Depending on the language, there will be both global and local variables available in a program.

In Python, we can check if a variable exists globally with the help of the globals() function. The globals() function returns a dictionary of all global variables.

print(globals())

#Output:
{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>}

To check for the existence of a variable globally, we can check if the variable is in globals.

Below is an example of how to check if a variable exists globally in Python.

variable = "this is a variable"

if 'variable' in globals():
   print("variable exists in global variables!")
else:
   print("variable doesn't exist in global variables!")

if 'other_variable' in globals():
   print("variable exists in global variables!")
else:
   print("other variable doesn't exist in global variables!")

#Output:
variable exists in global variables!
other variable doesn't exist in global variables!

Using Python to Check if Variable Exists Locally

We can also check if a variable exists locally with the help of the locals() function. The locals() function returns a dictionary of all local variables.

The locals() function can be useful if we are in a function or object and want to check if a variable exists only in that object or function.

To check for the existence of a variable locally, we can check if the variable is in locals().

Below is an example of how to check if a variable exists locally in Python.

def someFunction():
    variable = "this is a variable"
    if 'variable' in locals():
        print("variable exists in local variables!")
    else:
        print("variable doesn't exist in local variables!")
    if 'other_variable' in locals():
        print("other variable exists in local variables!")
    else:
        print("other variable doesn't exist in local variables!")

someFunction()

#Output:
variable exists in local variables!
other variable doesn't exist in local variables!

Hopefully this article has been useful for you to learn how to check if a variable exists in Python.

Other Articles You'll Also Like:

  • 1.  Python Check if Attribute Exists in Object with hasattr() Function
  • 2.  Write Inline If and Inline If Else Statements in Python
  • 3.  pandas Standard Deviation – Using std() to Find Standard Deviation
  • 4.  Get Username in Python using os module
  • 5.  Using Python to Count Odd Numbers in List
  • 6.  Set Widths of Columns in Word Document Table with python-docx
  • 7.  Using Python to Sum the Digits of a Number
  • 8.  How to Draw a Triangle in Python Using turtle Module
  • 9.  Using Python to Count Number of False in List
  • 10.  Perform Reverse Dictionary Lookup in Python

About The Programming Expert

The Programming Expert is a compilation of a programmer’s findings in the world of software development, website creation, and automation of processes.

Programming allows us to create amazing applications which make our work more efficient, repeatable and accurate.

At the end of the day, we want to be able to just push a button and let the code do it’s magic.

You can read more about us on our about page.

Reader Interactions

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Primary Sidebar

About The Programming Expert

the programming expert main image

Welcome to The Programming Expert. We are a group of US-based programming professionals who have helped companies build, maintain, and improve everything from simple websites to large-scale projects.

We built The Programming Expert to help you solve your programming problems with useful coding methods and functions in various programming languages.

Search

Learn Coding from Experts on Udemy

Looking to boost your skills and learn how to become a programming expert?

Check out the links below to view Udemy courses for learning to program in the following languages:

Copyright © 2023 · The Programming Expert · About · Privacy Policy