繁体   English   中英

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

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

我正在使用 VS Code 作为我的编辑器处理 Python 项目,当我在代码块之间放置注释时出现 Python 缩进错误。 具体来说:

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

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

当我调用 say(score0, score1) 时出现缩进错误,但如果我缩进注释以匹配周围的行,错误就会得到修复。 这是 Python 中的一般规则,还是使用 VS Code 的要求?

不以 # 开头的行被视为代码。

所以你的

"*** YOUR CODE HERE ***"

行实际上是代码,所以 Python 期望它之后的代码匹配它的缩进(因为 while 循环结束),并且不知道为什么say是缩进,所以它抛出缩进错误

所以这是 Python 的事情,而不是 VSCode 的事情

您可以在 python 中使用"进行多行注释,但它需要连续 3 行。一个示例是 Python 的文档字符串 例如,如果您有这样的主模块:

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

这是 Python 中的有效注释。 但是,正如您所指出的,您应该正确缩进。 因此,如果您想使用"""保留您的评论,您可以这样做:

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

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

请注意,您不需要在与 rest 相同的缩进处添加带有#的注释。

暂无
暂无

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

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