Python determines whether a variable exists
阿神
阿神 2017-07-05 10:35:30
0
1
1176

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

阿神
阿神

闭关修行中......

reply all(1)
学习ing

Reference article: Several classic questions on the road to learning Python

Python determines whether a variable exists

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() and globals().

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()
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template