【问题标题】:Python Programming: Multiline Comments before an Else statementPython 编程:Else 语句前的多行注释
【发布时间】:2015-03-28 12:50:36
【问题描述】:

当语法错误出现以下代码时,我正在使用 Python 中的简单 if-else 语句。

"""
A multi-line comment in Python
"""
if a==b:
    print "Hello World!"

"""
Another multi-line comment in Python
"""
else:
    print "Good Morning!"

此代码在“else”关键字处出现语法错误。

以下代码却没有:

"""
A multi-line comment in Python
"""
if a==b:
    print "Hello World!"

#One single line comment
#Another single line comment
else:
    print "Good Morning!"

谁能告诉我为什么会这样?为什么 Python 解释器不允许 if-else 语句之间有多行 cmets?

【问题讨论】:

标签: python if-statement comments


【解决方案1】:

您在代码中使用了多行字符串。所以你基本上是在写

if a==b:
    print "Hello World!"

"A string"
else:
    print "Good Morning!"

虽然 Guido Van Rossum(Python 的创建者)suggested to use multiline strings as comments,但 PEP8 建议使用多个单行 cmets 作为块。

见:http://legacy.python.org/dev/peps/pep-0008/#block-comments

【讨论】:

    【解决方案2】:

    不管怎样,你可以通过使用缩进来解决这个问题:

    a=2
    for b in range(2, 4): 
        """ 
        multi-line comment in Python
        """
        if a==b:
            print "Hello World!"
            """ 
            Another multi-line comment in Python
            """
        else:
            print "Good Morning!"
    

    ...但它不是特别漂亮,imo。

    由于 python 将三引号视为字符串,如上所述,错误的缩进基本上会缩短循环并中断程序的流程,从而在定义不明确的 else 语句上引发错误。

    所以我同意之前的 Q.s 和 cmets 观点,即多个单行引号是有利的。

    【讨论】:

      猜你喜欢
      • 2015-01-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多