This post will discuss how to check if a variable is defined in Python.

1. Using locals() function

To check if the variable is defined in a local scope, you can use the locals() function, which returns a dictionary representing the current local symbol table.

Download  Run Code

2. Using vars() function

Alternatively, you can use no-arg vars() function, which acts like locals() function.

Download  Run Code

3. Using dir() function

Without arguments, the dir() function returns the list of names in the current local scope.

Download  Run Code

4. Using globals() function

Finally, to check for the existence of a global variable, you can use the globals() function. It returns a dictionary representing the current global symbol table.

Download  Run Code

That’s all about determining whether a variable is defined in Python.