Home > Article > Backend Development > How to check if a variable exists
When calling a variable, if the variable is not defined, python will report an error.
#The solution is also very simple, which is to assign a null value to the variable in advance.
But you can also determine whether a variable name has been defined by calling the system's built-in function. There are 3 built-in functions that can be implemented.
res1 = 'test' in locals().keys() res2 = 'test' in dir() res3 = 'test' in vars().keys() print(res1,res2,res3) # 变量test暂时还没有定义,返回False test = "" # 定义变量test res4 = 'test' in locals().keys() res5 = 'test' in dir() res6 = 'test' in vars().keys() print(res4,res5,res6) # 变量test已经被定义了,返回True
Above, if you need to call a variable that is not sure whether it has been defined, you can first use the above function to add a judgment.
The above is the detailed content of How to check if a variable exists. For more information, please follow other related articles on the PHP Chinese website!