簡體   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