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

5
我在使用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语句之间使用多行注释?


3
这是一个字符串,而不是注释。 - Aran-Fey
在Python中如何编写多行注释?Python中的多行注释 - ashishbaghudana
2个回答

6

您的代码中使用了多行字符串。因此,您基本上是在编写

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

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

虽然 Python 的创始人 Guido Van Rossum 建议使用多行字符串作为注释,但 PEP8 建议使用多个单行注释作为块注释。
参见:http://legacy.python.org/dev/peps/pep-0008/#block-comments

4

值得一提的是,您可以通过缩进来解决这个问题:

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

...但我认为它不太美观。

正如上面所建议的,由于Python将三重引号视为字符串,因此错误的缩进会使循环被截断并中断程序的流程,在未定义的else语句上抛出错误。

因此,我同意先前问题和评论的观点,即使用多个单行引号更为可取。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接