Python - if or if invalid syntax error
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
错误
我尝试使用此 or
、if
语句的原因是 sheet2.cell_value(2,j)
在 Excel 中可能没有值(在这种情况下它将是 #VALUE!
) 在 Excel。因此,只有在单元格中有值的情况下,才必须评估 or sheet1.cell_value(i,8).lower()==sheet2.cell_value(2,j).lower())):
中的第二个 if 。我该如何解决这个问题?谢谢
在 Python 中禁止写入 (if ...)
或 if ...: if ...
。如果你想写"condition1, and, if that's true, also condition2",就写condition1 and condition2
(在这种情况下,如果condition1
为false,condition2
将不会被评估)。因此:
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())):
首先,稍微格式化一下也无妨。您不必将 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 (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
错误
我尝试使用此 or
、if
语句的原因是 sheet2.cell_value(2,j)
在 Excel 中可能没有值(在这种情况下它将是 #VALUE!
) 在 Excel。因此,只有在单元格中有值的情况下,才必须评估 or sheet1.cell_value(i,8).lower()==sheet2.cell_value(2,j).lower())):
中的第二个 if 。我该如何解决这个问题?谢谢
在 Python 中禁止写入 (if ...)
或 if ...: if ...
。如果你想写"condition1, and, if that's true, also condition2",就写condition1 and condition2
(在这种情况下,如果condition1
为false,condition2
将不会被评估)。因此:
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())):
首先,稍微格式化一下也无妨。您不必将 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