How does Python determine whether a variable exists?
if var:
var_exists = True
if not var:
var_exists = True
This way you can make a judgment before making a decision and report an error
学习ing2017-07-05 10:37:30
Reference article: Several classic questions on the road to learning Python
Method 1: Use
try: ... except NameError: ...
.
try:
var
except NameError:
var_exists = False
else:
var_exists = True
Method 2: Use the two built-in functions
locals()
andglobals()
.
locals()
: Dictionary-based way to access local variables. The keys are variable names and the values are variable values. globals()
: Dictionary-based way to access global variables. The keys are variable names and the values are variable values.
var_exists = 'var' in locals() or 'var' in globals()