-3
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,419
  • 1
  • 16
  • 28

4 Answers4

2

You have to enclose your VAR by quotes:

if 'VAR' in globals():
#  ^---^--- HERE
Corralien
  • 109,409
  • 8
  • 28
  • 52
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,419
  • 1
  • 16
  • 28
0

You have to put quotation marks around variable name:

if 'VAR' in globals():
...
Ahmad
  • 349
  • 1
  • 9
0

You can also use dir:

if 'VAR' in dir():
    print('TRUE')
else:
    print("FALSE")
Gino Mempin
  • 25,369
  • 29
  • 96
  • 135
  • 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