5

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

What is the difference between these two ways to comment?

Peter Mortensen
  • 30,030
  • 21
  • 100
  • 124
altarbza
  • 416
  • 6
  • 12

5 Answers5

6

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).
Peter Mortensen
  • 30,030
  • 21
  • 100
  • 124
Mr. Napik
  • 5,271
  • 3
  • 23
  • 18
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.

Peter Mortensen
  • 30,030
  • 21
  • 100
  • 124
kay
  • 24,516
  • 10
  • 94
  • 138
2

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

Peter Mortensen
  • 30,030
  • 21
  • 100
  • 124
David
  • 17,040
  • 9
  • 65
  • 97
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.

JCole
  • 37
  • 8
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.

Peter Mortensen
  • 30,030
  • 21
  • 100
  • 124