简体   繁体   English

Python 注释是否必须与周围的代码块一样缩进? (VS代码)

[英]Do Python comments have to be indented the same as surrounding code blocks? (VS Code)

I'm working on a Python project using VS Code as my editor, and I'm getting a Python indentation error when I place comments in between blocks of code.我正在使用 VS Code 作为我的编辑器处理 Python 项目,当我在代码块之间放置注释时出现 Python 缩进错误。 Specifically:具体来说:

while score0 < goal and score1 < goal:
    if player:
        ...
    else:
        ...
    player = other(player)

# END PROBLEM 5
# BEGIN PROBLEM 6
"*** YOUR CODE HERE ***"
    say(score0, score1)

I'm getting an indentation error when I evoke say(score0, score1), but the error gets fixed if I indent the comments to match the surrounding lines.当我调用 say(score0, score1) 时出现缩进错误,但如果我缩进注释以匹配周围的行,错误就会得到修复。 Is this a general rule in Python, or a requirement of using VS Code?这是 Python 中的一般规则,还是使用 VS Code 的要求?

Lines that do not start with a # are considered code.不以 # 开头的行被视为代码。

So your所以你的

"*** YOUR CODE HERE ***"

Line is actually code, so Python expects code after it to match it's indent (since the while loop is over), and doesn't know why say is indented, so it throws the Indentation Error行实际上是代码,所以 Python 期望它之后的代码匹配它的缩进(因为 while 循环结束),并且不知道为什么say是缩进,所以它抛出缩进错误

So this is a Python thing, not a VSCode thing所以这是 Python 的事情,而不是 VSCode 的事情

You can do a multiline comment in python with " but it needs to be 3 in a row. An example would be Python's docstrings For example, if you had a main module as such:您可以在 python 中使用"进行多行注释,但它需要连续 3 行。一个示例是 Python 的文档字符串 例如,如果您有这样的主模块:

def main(args):
    """
    Main method for running the selected arguments
    :param args: the arguments that are passed to main
    :return: None
    """

That is a valid comment in Python.这是 Python 中的有效注释。 However, as you noted, you should have it indented correctly.但是,正如您所指出的,您应该正确缩进。 So if you want to keep your comment using """ , you can do:因此,如果您想使用"""保留您的评论,您可以这样做:

while score0 < goal and score1 < goal:
    if player:
        ...
    else:
        ...
    player = other(player)

# END PROBLEM 5
# BEGIN PROBLEM 6
    """*** YOUR CODE HERE ***"""
    say(score0, score1)

Note that you do not need to put comments with the # on the same indentation as the rest.请注意,您不需要在与 rest 相同的缩进处添加带有#的注释。

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

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