When a variable is called, if the variable is not defined, then Python will make an error.
The method to be solved is also very simple, which is to assign a null value to the variable beforehand.
However, you can also call the system's built-in function to determine whether a variable name has been defined. 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) # variable test not yet defined , return falsetest = "" # define variable testres4 = ' Test ' in locals (). Keys () res5 = ' Test ' in dir () res6 = ' Test ' in VARs (). Keys () print (res 4,RES5,RES6) # variable test has been defined, returns true
Above, you can use the above function to add a judgment if you encounter a variable that is not sure whether you have defined it.
Python determines if a variable exists