6

Starting to program in Python, I see some scripts with comments using # and """ comments """.

What is the difference between these two ways to comment?

1

5 Answers 5

8

The best thing would be to read PEP 8 -- Style Guide for Python Code, but since it is longish, here is a three-liner:

  • Comments start with # and are not part of the code.
  • String (delimited by """ """) is actually called a docstring and is used on special places for defined purposes (briefly: the first thing in a module or function describing the module or function) and is actually accessible in the code (so it is a part of the program; it is not a comment).
Sign up to request clarification or add additional context in comments.

Comments

3

Triple quotes is a way to create a multi-line string and or comment:

"""
Descriptive text here
"""

Without assigning to a variable is a none operation that some versions of Python will completely ignore. PEP 8 suggests when to use block comment/strings, and I personally follow a format like this:

Example Google Style Python Docstrings

Comments

2

The string at the start of a module, class or function is a docstring:

that can be accessed with some_obj.__doc__ and is used in help(...). Whether you use "Returns 42" or """Returns 42""" is a matter of style, and using the latter one is more common, even for single-line documentation.

A # comment is just that, a comment. It cannot be accessed at runtime.

Comments

1

The # means the whole line is used for a comment while whatever is in between the two """ quotes is used as comments so you can write comments on multiple lines.

Comments

1

As the user in a previous answer stated, the triple quotes are used to comment multiple lines of code while the # only comments one line.

Look out though, because you can use the triple quotes for docstrings and such.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.