Python编程:Else语句之前的多行注释

时间:2015-01-29 10:25:42

标签: python if-statement comments

当使用以下代码出现语法错误时,我正在使用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语句之间进行多行注释?

2 个答案:

答案 0 :(得分:4)

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

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

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

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

请参阅:http://legacy.python.org/dev/peps/pep-0008/#block-comments

答案 1 :(得分:1)

对于它的价值,你可以通过使用缩进来解决这个问题:

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并评论多个单行报价是有利的。

相关问题