如何检查Python中是否存在两个变量?

YPC*_*ble 1 python

我想在Python中写一个像这个javascript的语句:

if (variable1 && variable2) { // do something only if both variables exist }

我尝试着:

if not (variable1 and variable2) is None: # do something only if both variables exist

但它不起作用...当我调试时,变量2没有定义,但函数仍然试图运行.出了什么问题?

use*_*ica 8

try:
    variable1
    variable2
except NameError:
    # Not there
else:
    # They exist
Run Code Online (Sandbox Code Playgroud)

这是一件非常难得的事情.在你做之前确保它确实是一个好主意.

请注意,设置的变量None与不存在的变量不同.如果你想检查变量是否是None,那么你只是弄乱了布尔逻辑语法:

if variable1 is not None and variable2 is not None:
    do_whatever()
Run Code Online (Sandbox Code Playgroud)

如果None保证在布尔上下文中将not 值视为true,则可以简化此操作.例如,如果variable1variable2re.search调用的结果,它们将是匹配对象,或者None您可以使用:

if variable1 and variable2:
    do_whatever()
Run Code Online (Sandbox Code Playgroud)