简体   繁体   English

Python编程:其他语句前的多行注释

[英]Python Programming: Multiline Comments before an Else statement

I was working with simple if-else statements in Python when a syntax error came up with the following code. 当以下代码出现语法错误时,我正在使用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!"

This code gives a syntax error at the "else" keyword. 此代码在“ else”关键字处给出语法错误。

The following code however does not: 但是,以下代码不会:

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

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

Could anyone tell me why this happens? 谁能告诉我为什么会这样? Why does the Python interpreter not allow multi-line comments between if-else statements? 为什么Python解释器不允许在if-else语句之间使用多行注释?

You're using multiline strings in your code. 您在代码中使用了多行字符串。 So you're basically writing 所以你基本上是在写

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

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

Although Guido Van Rossum (the creator of Python) suggested to use multiline strings as comments , PEP8 recommends to use multiple single line comments as block. 尽管Guido Van Rossum(Python的创建者) 建议使用多行字符串作为注释 ,但PEP8建议使用多个单行注释作为块。

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

For what it is worth, you can get around this problem by using indentation: 对于它的价值,您可以使用缩进解决此问题:

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

... but it is not particularly pretty, imo. ...但是它不是特别漂亮,imo。

As python treats triple quotes just as strings, as suggested above, the wrong indentation basically cuts the loops short and interrupts the program's flow, throwing an error on the ill-defined else statement. 正如上面所建议的,由于python将三重引号当作字符串对待,因此,错误的缩进基本上会缩短循环并中断程序的流程,从而在错误定义的else语句上引发错误。

So I agree with the previous Qs and comments sentiment that multiple single line quotes are favourable. 因此,我同意前面的问答和评论观点,即多行单行引号是有利的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM