Tags
Asked 3 years ago
13 Aug 2021
Views 406
Carmelo

Carmelo posted

Check if a variable exists

Check if a variable exists
sachin

sachin
answered May 2 '23 00:00

if you mean to check if a variable exists in Python or not.than
you can use the in operator with the globals() or locals() built-in functions.

globals() :


variable_name = "Hello, world!"

if 'variable_name' in globals():
    print("Variable exists")
else:
    print("Variable does not exist")

This code checks if the variable variable_name exists in the global namespace using the in operator with the globals() function. If the variable exists, it prints "Variable exists", otherwise it prints "Variable does not exist".

locals() :


def my_function():
    local_variable = 123
    
    if 'local_variable' in locals():
        print("Variable exists")
    else:
        print("Variable does not exist")
        
my_function()

This code defines a function my_function() that creates a local variable local_variable. The code then checks if the variable exists in the local namespace using the in operator with the locals() function. If the variable exists, it prints "Variable exists", otherwise it prints "Variable does not exist".

Both of these methods are simple and effective ways to check if a variable exists in Python, and can be used in a wide range of scenarios.
Post Answer