【问题标题】:Do Python comments have to be indented the same as surrounding code blocks? (VS Code)Python 注释是否必须与周围的代码块一样缩进? (VS代码)
【发布时间】:2020-04-03 22:55:02
【问题描述】:

我正在开发一个使用 VS Code 作为编辑器的 Python 项目,当我在代码块之间放置 cmets 时出现 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) 时出现缩进错误,但如果我缩进 cmets 以匹配周围的行,该错误就会得到修复。这是 Python 中的一般规则,还是使用 VS Code 的要求?

【问题讨论】:

  • IDLE 也是如此
  • 您是说“*** YOUR CODE [...]”行是注释吗?因为它不是,并且是有效的 python 代码行,所以它必须匹配其余代码

标签: python visual-studio-code indentation


【解决方案1】:

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

所以你的

"*** YOUR CODE HERE ***"

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

所以这是 Python 的东西,而不是 VSCode 的东西

【讨论】:

    【解决方案2】:

    您可以在 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)
    

    请注意,您不需要将带有# 的 cmets 放在与其余部分相同的缩进上。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-12-26
      • 2019-02-13
      • 2019-11-08
      • 2011-10-02
      • 1970-01-01
      • 2010-11-07
      • 2022-01-13
      相关资源
      最近更新 更多