Python - 如果或者语法错误无效

时间:2015-03-25 14:58:21

标签: python syntax syntax-error

我在Python中有以下代码行:

if (sheet1.cell_value(i,8).lower()==sheet2.cell_value(0,j).lower() or (if hasattr(sheet2.cell_value(2,j), 'lower'): if sheet1.cell_value(i,8).lower()==sheet2.cell_value(2,j).lower())):

我目前收到SyntaxError: invalid syntax错误

我尝试使用此orif语句的原因是sheet2.cell_value(2,j)在Excel中可能没有值(在这种情况下它将是#VALUE!) Excel中。因此,只有在单元格中有值时才必须评估or sheet1.cell_value(i,8).lower()==sheet2.cell_value(2,j).lower())):中的第二个if。如何解决这个问题?感谢

2 个答案:

答案 0 :(得分:1)

首先,一点点格式化不会受到伤害。您不必将if声明粉碎到一行。此外,您现在的方式 无效。将您的if分成不同的行

其次,您有括号问题。目前,括号跨越语句(通过冒号)。

此块对齐括号。我删除了整个声明周围的那些。相反,我们有第一个or条件。如果评估为True,那么我们进行第二次相等检查。如果通过,则其余逻辑进入该块。

if sheet1.cell_value(i,8).lower()==sheet2.cell_value(0,j).lower() or  hasattr(sheet2.cell_value(2,j), 'lower'): 
    if sheet1.cell_value(i,8).lower()==sheet2.cell_value(2,j).lower():
        # Do stuff here

答案 1 :(得分:0)

Python中禁止编写(if ...)if ...: if ...。如果你想写“condition1,如果那是真的,也是条件2”,只需写condition1 and condition2(在这种情况下,如果condition2为假,则不会评估condition1)。因此:

if (sheet1.cell_value(i,8).lower()==sheet2.cell_value(0,j).lower() or (hasattr(sheet2.cell_value(2,j), 'lower') and sheet1.cell_value(i,8).lower()==sheet2.cell_value(2,j).lower())):