Home  >  Q&A  >  body text

Python determines whether a variable exists

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

阿神阿神2635 days ago1112

reply all(1)I'll reply

  • 学习ing

    学习ing2017-07-05 10:37:30

    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()

    reply
    0
  • Cancelreply