Python开发 - 意外的缩进问题

时间:2011-06-13 10:29:54

标签: python django

我最近在一些以前正在运行的代码中插入了一个if语句。当我在if语句的开头运行它时,我现在得到一个意外的缩进错误。

   ImpressionsBasedOnWeight = setImpressionsBasedOnWeight(setImpressionsBasedOnWeightData)
   impressions = data[2]
       if reportSuite.RP_UniqueUsers > weighted_impressions:
           users = weighted_impressions
       else:
           users = reportSuite.RP_UniqueUsers
   Pages_in_thousands = impressions / 1000

如果我删除缩进,它就会失败,说它需要缩进,如果我再添加缩进,则说明意外缩进...

2 个答案:

答案 0 :(得分:6)

impressions = data[2]是一个简单的分配。之后压痕应该没有变化。因此,您需要impressions = ..if ..使用相同的缩进:

ImpressionsBasedOnWeight = setImpressionsBasedOnWeight(setImpressionsBasedOnWeightData)
impressions = data[2]
if reportSuite.RP_UniqueUsers > weighted_impressions:
    users = weighted_impressions
else:
    users = reportSuite.RP_UniqueUsers
Pages_in_thousands = impressions / 1000

此外,请确保您没有在标签和空格之间切换以进行缩进。您可以设置一些指标来显示标签的符号,一个好的编辑器应该在您选择整个代码时统一缩进,按Tab然后按Shift+Tab

答案 1 :(得分:2)

为什么将if放入缩进?

   ImpressionsBasedOnWeight = setImpressionsBasedOnWeight(setImpressionsBasedOnWeightData)
   impressions = data[2]
   if reportSuite.RP_UniqueUsers > weighted_impressions:
       users = weighted_impressions
   else:
       users = reportSuite.RP_UniqueUsers
   Pages_in_thousands = impressions / 1000