• 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 is Defined in Python

How to Check if Variable is Defined in Python

June 22, 2022 Leave a Comment

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

try:
    print(variable)
except NameError:
    print("variable isn't defined")

#Output:
variable isn't defined.

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

variable = "this is a variable"

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

#Output:
variable is defined in global variables!

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

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

someFunction()

#Output:
variable is defined 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 isn’t defined.

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

Checking to see if a variable is defined 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 isn’t defined, then a NameError will be raised and we can handle the error in the except block.

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

try:
    print(variable)
except NameError:
    print("variable isn't defined")

#Output:
variable isn't defined.

If instead, you are trying to check if an attribute is defined in an object, you can check if an attribute is defined in an object with the hasAttr() function.

Using Python to Check if Variable is Defined as Global Variable

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 is defined as a global variable 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 if a variable is defined as a global variable, we can check if the variable is in globals.

Below is an example of how to check if a variable is defined as a global variable in Python.

variable = "this is a variable"

if 'variable' in globals():
   print("variable is defined in global variables!")
else:
   print("variable isn't defined in global variables!")

if 'other_variable' in globals():
   print("variable is defined in global variables!")
else:
   print("other variable isn't defined in global variables!")

#Output:
variable is defined in global variables!
other variable isn't defined in global variables!

Using Python to Check if Variable is Defined as Local Variabley

We can also check if a variable is defined as a local variable 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 is defined only in that object or function.

To check if a variable is defined as a local variable, we can check if the variable is in locals().

Below is an example of how to check if a variable is defined as a local variable in Python.

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

someFunction()

#Output:
variable is defined in local variables!
other variable isn't defined in local variables!

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

Other Articles You'll Also Like:

  • 1.  Using Python to Get and Print First N Items in List
  • 2.  Subtract Seconds from Datetime Variable Using Python timedelta() Function
  • 3.  Using Python to Reverse Tuple
  • 4.  Python Check if Object Has Attribute
  • 5.  Using Python to Check If List of Words in String
  • 6.  List of Turtle Shapes in Python
  • 7.  Convert Integer to Bytes in Python
  • 8.  Using pandas to_csv() Function to Append to Existing CSV File
  • 9.  pandas drop – Drop Rows or Columns from DataFrame
  • 10.  Pythagorean Theorem in Python – Calculating Length of Triangle Sides

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