简体   繁体   English

Python-如果或无效语法错误

[英]Python - if or if invalid syntax error

I have the following line of code in Python: 我在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())):

I currently get a SyntaxError: invalid syntax error 我目前收到一个SyntaxError: invalid syntax错误

The reason I try to use this or , if statements is that sheet2.cell_value(2,j) may not have a value in Excel (in which case it would be #VALUE! ) in Excel. 我尝试使用this or if语句的原因是, sheet2.cell_value(2,j)在Excel中可能没有值(在这种情况下为#VALUE! )。 Thus, the second if in the or sheet1.cell_value(i,8).lower()==sheet2.cell_value(2,j).lower())): must be evaluated only in case there is a value in the cell.. How can I fix that? 因此,第二个if或sheet1.cell_value(i,8).lower()==sheet2.cell_value(2,j).lower())):仅在单元格中有值的情况下才进行评估..我该如何解决? Thanks 谢谢

First, a little bit of formatting wouldn't hurt. 首先,一点格式化都不会受到伤害。 You don't have to smash your if statement onto one line. 您不必将if语句粉碎到一行上。 Additionally, the way you have it now is invalid. 此外,你有现在的方法无效的。 Break your if s onto separate lines if分成不同的行

Second, you have parenthesis issues. 其次,您有括号问题。 Currently, the parenthesis are going across statements (through the colon). 当前,括号会跨越多个语句(通过冒号)。

This block aligns the parenthesis. 该块使括号对齐。 I removed the ones surrounding the entire statement. 我删除了整个语句周围的内容。 Instead, we have your first or conditional. 相反,我们有您的第一个or有条件的。 If that evaluates to True , then we do your second equality check. 如果该结果为True ,那么我们将进行第二次相等性检查。 If that passes, the rest of your logic goes into that block. 如果通过了,那么其余的逻辑将进入该块。

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

Writing (if ...) or if ...: if ... are both forbidden in Python. 在Python中都禁止编写(if ...)if ...: if ...两者。 If you want to write "condition1, and, if that's true, also condition2", just write condition1 and condition2 (in which case condition2 will not be evaluated if condition1 is false). 如果要编写“ condition1,并且如果也为true,则为condition2”,则只需编写condition1 and condition2 (在这种情况condition2如果condition1为false则不会评估condition1 )。 Thus: 从而:

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