Python is used to determine whether a variable has been defined. python is used to determine the definition of a variable.
It is very important for Python to determine whether a variable has been defined. This article describes how to implement this function.
In fact, there are many methods in Python to determine whether a variable has been defined. The two most common examples are as follows:
Method 1: try again t:
def isset(v): try : type (eval(v)) except : return 0 else : return 1
Usage:
if isset('user_name'): print 'user_name is defined' else print 'user_name is not defined'
Method 2: Use the namespace:
'varname' in locals().keys()'varname' in dir()
This example is for reference only. Readers can continue to summarize other methods in Python programming practices.
How does python determine whether a variable has been defined?
In Python, there are actually many ways to determine whether a variable has been defined. Method 1: try using t [mw_shl_code = python, true] def isset (v): try: type (eval (v) using T: return 0 else: return 1 [/mw_shl_code] usage: [mw_shl_code = python, true] if isset ('user _ name '): print 'user _ name is defined' else print 'user _ name is not defined' [/mw_shl_code] Method 2: Use the namespace [mw_shl_code = python, true] 'varname' in locals (). keys () 'varname' in dir () [/mw_shl_code] The second method is recommended for judging
Python determines whether a variable is defined
The built-in functions vars (without parameters) and locals return a dictionary of all local variables defined in the current scope. >>> 'A' in vars () False >>> a = 1 >>> 'A' in vars () True >>> B = 2 >>> locals ()