【问题标题】:How to comment each condition in a multi-line if statement?如何在多行 if 语句中注释每个条件?
【发布时间】:2014-05-19 20:06:35
【问题描述】:

我想要一个多行的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 语句?

【问题讨论】:

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


【解决方案1】:

不要使用\,使用括号:

if (CONDITION1 or
    CONDITION2 or
    CONDITION3):

而且你可以随意添加cmets:

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

Python 允许在带括号的表达式中使用换行符,当使用 cmets 时,就表达式而言,换行符被视为位于注释开始之前。

演示:

>>> 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!

【讨论】:

    猜你喜欢
    • 2013-12-17
    • 2015-01-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-20
    • 1970-01-01
    • 2017-09-25
    • 1970-01-01
    相关资源
    最近更新 更多