Python运行报expected indented block无效语法错误求排查
报错根因
触发expected indented block - invalid syntax错误的直接原因是多行条件判断的续行缩进不规范,破坏了Python的代码块层级识别规则。
你代码中两处三层嵌套if的多行条件都用了反斜杠\续行,但续行后的and语句缩进比if声明行少了4个空格,导致解释器判定最内层if语句在第一行末尾就已经结束,冒号后没有跟随对应缩进的执行块,直接抛出语法错误。报错定位到qr_os = qr_os.append(qr2.iloc[i],ignore_index=True)行,是因为解释器扫到这行时才发现块结构不匹配。
修复方案
- 弃用容易出错的反斜杠续行写法,改用圆括号包裹多行判断条件,不需要额外加反斜杠,缩进容错性更高
- 统一嵌套代码的缩进规则:每一层嵌套比上一层多缩进4个空格,if/for/while等语句的冒号后,执行代码必须比声明行多一层缩进
- 补充提示:pandas 2.0+版本已经正式删除
DataFrame.append()API,长期运行建议替换为pd.concat()实现行拼接,避免版本兼容问题
修正后可运行代码
d = qr2.iloc[0].to_dict() for i in list(d.keys()): d[i] = np.nan for i in range(len(qr2)): if qr2.iloc[i]['PrimaryRiskId'] not in list(aID): if qr2.iloc[i]['LinkageLinkType'] != 'B2B_COUNTER_TRADE': if (qr2.iloc[i]['CreatedBy'] != 'koala_manual' and qr2.iloc[i]['Book'] not in {'PIZH','SIBZ','IIBZ','OTCL','FXNG'} and qr2.iloc[i]['SubCategoryValuation'] not in {'EQCertificate','EQCertificatePlus','EQCappucino','EQCliquetUnlimitedDownside'}): qr_rec = qr_rec.append(qr2.iloc[i], ignore_index=True) d[list(d.keys())[0]] = 'records which are in cleaned QueryResults and are not in TMRActivity' qr_rec = qr_rec.append(d, ignore_index=True) #### QueryResults exceptions which are out of scope### qr_os = qr2.iloc[[0,1]] for i in range(len(qr2)): if qr2.iloc[i]['PrimaryRiskId'] not in list(aID): if qr2.iloc[i]['LinkageLinkType'] == 'B2B_COUNTER_TRADE': if (qr2.iloc[i]['CreatedBy'] == 'koala_manual' and qr2.iloc[i]['Book'] in {'PIZH','SIBZ','IIBZ','OTCL','FXNG'} and qr2.iloc[i]['SubCategoryValuation'] in {'EQCertificate','EQCertificatePlus','EQCappucino','EQCliquetUnlimitedDownside'}): qr_os = qr_os.append(qr2.iloc[i], ignore_index=True) d[list(d.keys())[0]] = 'records which are in cleaned QueryResults and are not in TMRActivity and should be treated as o/s' qr_os = qr_os.append(d, ignore_index=True)
内容的提问来源于stack exchange,提问作者Paula Ciesielska
相关产品推荐
相关产品推荐

