为什么IF:没有正确评估这个变量?

时间:2014-05-28 01:49:02

标签: python-2.7

我创建了一个函数,根据传递给它的参数创建另一个变量。

如下:

def process_command(var1, var2, var3, var4):
  if var3 == ":help":
    reply = 'Help command received.'
  if var3 == ':status':
    reply = 'Status command received.'
  if var3 == ':start':
    reply = 'Start command received.'
 if var3 == ':stop':
    reply = 'Stop command received.'
  if var3 == ':shutdown':
    reply = 'Shutdown command received.'
  else:
    reply = '%s command unknown.\nSend :help for a list of commands.' % msg

当我的程序将:help(或任何其他人)分配给var3并调用此函数时,它会直接跳到ELSE:行而不是处理预期的{{1}行。

我的第一个想法是在文本中使用冒号存在问题,所以我将其删除 - 结果相同。它在此函数中没有看到if var3 == ':help':'help'

当我将':help'分配为':help'它处理else语句并以:

响应
var3

为了以防万一,我已经尝试强迫它成为:help command unknown. Send :help for a list of commands. ,但这也没有用。我试着切出结肠,没有骰子。

为什么当我的变量看起来设置为str()时,它不会被视为':help'

2 个答案:

答案 0 :(得分:3)

到达时,始终会评估

if个语句。如果您希望仅在先前条件失败时评估条件,则需要使用elif

if ...:
   ...
elif ...:
   ...
else:
   ...

答案 1 :(得分:2)

如果您不希望运行每个if语句,请使用elif。否则,每个人都会被召唤。

foo = True
if foo:
    print 'yes'
    #Gets called
if not foo:
    print 'no'
else:
    print 'yes' #Also gets called

基本上,您的代码已达到reply = 'Help command received.',但随后转到if var3 == ':shutdown':,然后触发else,重新分配reply

这是您更新的代码:

def process_command(var1, var2, var3, var4):
  if var3 == ":help":
    reply = 'Help command received.'
  elif var3 == ':status':
    reply = 'Status command received.'
  elif var3 == ':start':
    reply = 'Start command received.'
  elif var3 == ':stop':
    reply = 'Stop command received.'
  elif var3 == ':shutdown':
    reply = 'Shutdown command received.'
  else:
    reply = '%s command unknown.\nSend :help for a list of commands.' % msg