繁体   English   中英

Python-如果或无效语法错误

[英]Python - if or if invalid 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错误

我尝试使用this or if语句的原因是, sheet2.cell_value(2,j)在Excel中可能没有值(在这种情况下为#VALUE! )。 因此,第二个if或sheet1.cell_value(i,8).lower()==sheet2.cell_value(2,j).lower())):仅在单元格中有值的情况下才进行评估..我该如何解决? 谢谢

首先,一点格式化都不会受到伤害。 您不必将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

在Python中都禁止编写(if ...)if ...: if ...两者。 如果要编写“ condition1,并且如果也为true,则为condition2”,则只需编写condition1 and condition2 (在这种情况condition2如果condition1为false则不会评估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())):

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM