蟒蛇如果条件不能正常工作如预期
问题描述:
在onClick_button事件我有一个if条件来显示messagedialog如果条件失败或执行其余的语句。 基本上,如果条件是检查textctrl是否有价值或不。如果有值执行else语句。蟒蛇如果条件不能正常工作如预期
这是第一次在tc(textctrls)中带有msgdlg的任何值,但是当在dlg上单击确定并在tc中添加一些值时,msgdlg仍然会在执行else时弹出。
非常感谢您的帮助。 我检查了所有的缩进。
def onClick_button_new(self, event):
self.list_box.Clear()
varstr = "csv"
if [(self.tc1.GetValue() == "") or (self.tc2.GetValue() == "")]:
dial = wx.MessageDialog(None, 'No file specified. Please specify relevant file', 'Error', wx.OK)
dial.ShowModal()
else:
file1 = subprocess.check_output("cut -d '.' -f2 <<< %s" %self.var1, shell = True, executable="bash")
file1type = file1.strip()
print file1type
file2 = subprocess.check_output("cut -d '.' -f2 <<< %s" %self.var2, shell = True, executable="bash")
file2type = file2.strip()
if varstr in (file1type, file2type):
print "yes"
else:
dial = wx.MessageDialog(None, ' Invalid file format. Please specify relevant file', 'Error', wx.OK)
dial.ShowModal()
答
根据输入
[(self.tc1.GetValue() == "") or (self.tc2.GetValue() == "")]
或者是[True]
或[False]
。在任何情况下都是非空的列表。这将被解释为True
;
if [False]:
do_something()
在这个例子中
do_something()
就一定会执行。
解决这个问题,你需要删除括号[]
:
if (self.tc1.GetValue() == "") or (self.tc2.GetValue() == ""):
...
答
你有你的布尔逻辑混合起来,创建一个列表对象(它总是非空和总是真)。你想用and
和不使用列表:
if self.tc1.GetValue() == "" and self.tc2.GetValue() == "":
你不应该使用[...]
列表一个布尔测试,因为这只是创建一个列表对象不是空的,因而总是被视为真正的布尔上下文,不管所包含的比较结果:
>>> [0 == 1 or 0 == 1]
[False]
>>> bool([0 == 1 or 0 == 1])
True
+0
非常感谢。那工作。 –
答
不需要你的方法效果比较空字符串:
if not self.tc1.GetValue() and not self.tc2.GetValue():
看到这个职位:Most elegant way to check if the string is empty in Python?
非常感谢。这工作。 –