如何在多行if语句中注释每个条件?

时间:2014-04-07 14:07:57

标签: python python-3.x comments conditional multiline

我希望有一个多行if语句,例如:

if CONDITION1 or\
   CONDITION2 or\
   CONDITION3:

我想评论每行源代码的结尾

if CONDITION1 or\ #condition1 is really cool
   CONDITION2 or\ #be careful of condition2!
   CONDITION3:    #see document A sec. B for info

我被禁止这样做,因为python将它全部视为一行代码并报告SyntaxError: unexpected character after line continuation character

我应该如何实施和记录冗长的多行if语句?

1 个答案:

答案 0 :(得分:16)

请勿使用\,请使用括号:

if (CONDITION1 or
    CONDITION2 or
    CONDITION3):

您可以随意添加评论:

if (CONDITION1 or  # condition1 is really cool
    CONDITION2 or  # be careful of conditon2!
    CONDITION3):   # see document A sec. B for info

Python允许在带括号的表达式中使用换行符,并且在使用注释时,只要涉及表达式,就会将新行看作位于注释开始之前。

演示:

>>> CONDITION1 = CONDITION2 = CONDITION3 = True
>>> if (CONDITION1 or  # condition1 is really cool
...     CONDITION2 or  # be careful of conditon2!
...     CONDITION3):   # see document A sec. B for info
...     print('Yeah!')
... 
Yeah!