如果声明没有分隔内容

时间:2015-01-21 13:14:36

标签: windows python-2.7

请参阅以下代码段:

exclude = ["BURSAR", "SHOP"]
for name in exclude:
    if name in machineName: # machineName is defined further up in the script.
        inputText.insert("end", machineName + " has been excluded.\n")
    else:
        command = subprocess.Popen( commands here...)

它的工作是排除任何包含其名称中某些单词的机器。

目前,如果我将两台机器传递给脚本,其中一台机器被称为“BURSAR3”(例如),它将注册应该被排除的事实,并运行inputText来显示该事实。不幸的是,它也继续将名称传递给下面的命令,而不应该。我甚至可以将'else:'替换为'if name not in exclude:',它仍然会以同样的方式失败!

我在这里做错了什么?看起来应该这么简单......

谢谢, 克里斯。 附:道歉,如果标题是垃圾 - 我想不出如何更好地定义它......

1 个答案:

答案 0 :(得分:0)

else

之后使用可选的for
exclude = ["BURSAR", "SHOP"]
for name in exclude:
    if name in machineName: # machineName is defined further up in the script.
        inputText.insert("end", machineName + " has been excluded.\n")
        break
else:
    command = subprocess.Popen( commands here...)

else仅在for循环自然完成时执行,而不会遇到break。因此,如果没有列入黑名单的单词出现在机器名称中,则执行else块。

当然,有一种更简单的方法可以做到这一点:

exclude = ["BURSAR", "SHOP"]
if any((name in machineName for name in exclude)): # machineName is defined further up in the script.
    inputText.insert("end", machineName + " has been excluded.\n")
else:
    command = subprocess.Popen( commands here...)