简体   繁体   中英

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. 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. Is this a general rule in Python, or a requirement of using 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

So this is a Python thing, not a VSCode thing

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:

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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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