Skip to content
  • (+91) 9409548155
  • support@appdividend.com
  • Home
  • Pricing
  • Instructor
  • Tutorials
    • Laravel
    • Python
    • React
    • Javascript
    • Angular
  • Become A Tutor
  • About Us
  • Contact Us
Menu
  • Home
  • Pricing
  • Instructor
  • Tutorials
    • Laravel
    • Python
    • React
    • Javascript
    • Angular
  • Become A Tutor
  • About Us
  • Contact Us
  • Home
  • Pricing
  • Instructor
  • Tutorials
    • Laravel
    • Python
    • React
    • Javascript
    • Angular
  • Become A Tutor
  • About Us
  • Contact Us
Python

How to Check If a Variable Exists in Python

  • 04 Aug, 2025
  • Com 1
Cheking if a variable exists in Python

To check if a variable exists in Python, you can use scope-specific dictionaries (locals(), globals(), vars()) or exception handling (try/except).

Method 1: Using try-except Block

Using try-except to check if a variable exists in Python

The try/except mechanism attempts to access the variable and catches a NameError if it doesn’t exist. 

It is a robust approach that works reliably with all cases, including local, global, and non-local variables.

If it exists, we set our flag variable to True; otherwise, we set it to False.

try:
    print(main_var)
    exists = True
except NameError:
    exists = False
print("Variable exists:", exists)

# Output: Variable exists: False


# Define variable and retry
main_var = 19
try:
    print(main_var)
    exists = True
except NameError:
    exists = False
print("Variable exists:", exists)

# Output: Variable exists: True

It is a general-purpose checking, especially in dynamic or unpredictable environments.

Method 2: Using locals() for local scope

The locals() function returns a dictionary containing the variables defined in the local scope.

If you define a variable inside a function or block scope, it automatically becomes a local variable.

Using the in operator, we need to check if a key exists in the locals() dictionary. With the help of an if condition, it returns True if the variable exists and False otherwise.

Checking If a Variable Exists in Python using locals() dictionary

my_variable = 19

if 'my_variable' in locals():
  print(True)
else:
  print(False)

# Output: True

In this code, we created a custom function that checks a variable within the local scope. Since we get the output True, the variable exists in the local dict (scope).

What if we pass a variable name that does not exist in the local scope? Let’s find out.

if 'my_variable' in locals():
    print(True)
else:
    print(False)

# Output: False

We received the output False, which indicates that the variable does not exist.

Method 3: Using globals()

The globals() is a built-in function that returns the dictionary of the current global symbol table.

If you define a variable outside a function or block scope, it automatically becomes a global variable.

Using the ‘in’ operator, the ‘if’ condition, and the ‘globals()‘ function, we can check for a specific condition.

If the condition returns True, it means the variable exists in the global scope; otherwise, we get the output False.

Using globals() to check if the variable exists in global scope in Python

# Define a global variable
my_variable = 13


def check_variable_existence_global():

    if "my_variable" in globals():
        print(True)
    else:
        print(False)


# Call the function
check_variable_existence_global()

# Output: True

In the above code, we defined a variable, my_variable, outside a functional scope, which places it in the global scope. Since the output is True, the variable exists.

Let’s check if for an undefined variable.

def check_variable_existence_global():

    my_variable = 13

    if "my_variable" in globals():
        print(True)
    else:
        print(False)


# Call the function
check_variable_existence_global()

# Output: False

As expected, we got the False output. It is a direct approach for checking global scopes.

That’s all!

Post Views: 30
Share on:
Krunal Lathiya

With a career spanning over eight years in the field of Computer Science, Krunal’s expertise is rooted in a solid foundation of hands-on experience, complemented by a continuous pursuit of knowledge.

How to Convert Set to Tuple and Tuple to Set in Python
JavaScript Object keys() Method

1 Comment

  1. Esportaren

    March 30, 2023 at 1:50 pm

    Thanks for this! I will give that a ago , hopefully my REST endpoint which relies on a global variable being a certain value wont return a 500 if the variable doesnt exist.

    Reply

Leave a Reply Cancel reply

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

Address: TwinStar, South Block – 1202, 150 Ft Ring Road, Nr. Nana Mauva Circle, Rajkot(360005), Gujarat, India

Call: (+91) 9409548155

Email: support@appdividend.com

Online Platform

  • Pricing
  • Instructors
  • FAQ
  • Refund Policy
  • Support

Links

  • About Us
  • Contact Us
  • Privacy Policy
  • Terms of services

Tutorials

  • Angular
  • React
  • Python
  • Laravel
  • Javascript
Copyright @2024 AppDividend. All Rights Reserved
Appdividend