0

i need to know if the variable is defined or not in python without making error because i am working on a project has a lot of variables and i need to know if the variable is defined to know if the operation has been do or not

is there method or way to know if the variable defind or not without makeing error ?

now i use this code below but it makes error to know if the variable defined or not :

try:
    variable
    print("this variable is defined")
except:
    print("this variable is not defined")
  • There shouldn't even be an undefined variable in your program. When something like this happens, it usually means that the design of the program is simply bad. – Matthias Oct 24 '22 at 21:49

1 Answers1

2

You can check inside globals,

if 'variable' in globals():
    print("this variable is defined")
else:
    print("this variable is not defined")
Rahul K P
  • 15,740
  • 4
  • 35
  • 52