简体   繁体   English

带注释的块/缩进干扰代码

[英]Commented blocks/indents interfering with code

The problem is best explained by just showing the code: 仅显示代码可以最好地说明问题:

a = True
b = True
while True:
    """
    A
    """
    if a == True:
        pass
    """
    B
    """
    elif b == True:
        pass

The issue being that there is a syntax error at "elif b", though when removing the comments, the issue disappears. 问题是“ elif b”处存在语法错误,尽管删除注释时问题仍然消失。 I tried removing the indents on the comments which resulted in an expected indent on the closing comment line after "A". 我尝试删除注释上的缩进,从而导致在“ A”之后的结束注释行上出现预期的缩进。 I know I could switch to using "#" to comment sections, though """ makes things much clearer and is more convenient for large chunks. Perhaps I'm missing something obvious, I would appreciate any help. 我知道我可以改用“#”来注释部分,尽管“”“可以使事情变得更清晰,也更方便于大块代码。也许我遗漏了一些明显的东西,我将不胜感激。

String literals aren't comments. 字符串文字不是注释。 You can sometimes sort of pretend they're comments, but they're not, and the fact that they're not is finally biting you. 有时您可以假装它们是评论,但不是,而事实并非如此,这最终会伤到您。

An elif has to appear immediately after the end of the block associated with the preceding if or elif . elif必须在与前面的ifelif相关联的块的结尾之后立即出现。 There can be comments and whitespace in between, but no statements, and strings count. 中间可以有注释和空格,但没有语句,字符串也没有计数。 Use real comments, with # . 使用带有#真实注释。

If you really want to keep pretending strings are comments, you can indent the B string into the body of the if , but it won't line up cleanly with the block it's intended to be a comment on, and you'll just keep having to mess with your formatting to patch up the differences between comments and string literals. 如果您真的想假装字符串是注释,则可以将B字符串缩进if的主体中,但是它不会与要注释的块清晰地对齐,您将继续拥有弄乱您的格式以修补注释和字符串文字之间的差异。

You're creating a new string when you use """triple quotes""" . 当您使用"""triple quotes"""时,您正在创建一个新字符串。 So, you essentially have an un-indented block of code before your elif, which requires a preceding if statement. 因此,在您的elif之前,您实际上有一个未缩进的代码块,这需要前面的if语句。 The improper tabbing on the quotes ends your if block. 引号上的不正确制表符将终止您的if块。 Once your parser reaches the elif block, it doesn't have a matching if block, hence the error. 解析器到达elif块后,便没有匹配的if块,因此会出现错误。

Triplequotes are used as docstrings in places, and can act like comments, but they're not actually comments. 三引号在地方用作文档字符串,可以充当注释,但实际上不是注释。

Reference (search for """) 参考(搜索“””)

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

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