-2
if VAR in globals():
    print('TRUE')
else:
    print("FALSE")

I got this error:

  File "c:/Users/Admin/Desktop/Project_Nuôi_FB/te1.py", line 2, in <module>
    if VAR in globals():
NameError: name 'VAR' is not defined

How do I check the existence of a variable?

Hemerson Tacon
  • 2,339
  • 1
  • 15
  • 26

4 Answers4

2

You have to enclose your VAR by quotes:

if 'VAR' in globals():
#  ^---^--- HERE
Corralien
  • 70,617
  • 7
  • 16
  • 36
0

globals() return a dictionary with string keys. Thus to check if a variable named VAR is defined you need to do the following:

if 'VAR' in globals():
    print('TRUE')
else:
    print("FALSE")
Hemerson Tacon
  • 2,339
  • 1
  • 15
  • 26
0

You have to put quotation marks around variable name:

if 'VAR' in globals():
...
Ahmad
  • 316
  • 1
  • 7
0

You can also use dir:

if 'VAR' in dir():
    print('TRUE')
else:
    print("FALSE")
Gino Mempin
  • 19,150
  • 23
  • 79
  • 104
  • The output `dir()` and `globals()` can be different: [difference between locals() and globals() and dir() in python](https://stackoverflow.com/q/32003472/2745495]) – Gino Mempin Jul 31 '21 at 01:15