📜  undef 变量 - Python 代码示例

📅  最后修改于: 2022-03-11 14:46:53.498000             🧑  作者: Mango

代码示例1
Testing if a Variable Is Defined
Credit: Hamish Lawson

Problem
You want to take different courses of action based on whether a variable is defined.

Solution
In Python, all variables are expected to be defined before use. The None object is a value you often assign to signify that you have no real value for a variable, as in:

try: x
except NameError: x = None
Then it’s easy to test whether a variable is bound to None:

if x is None:
    some_fallback_operation(  )
else:
    some_operation(x)