Python Tutorial · Python Basics · Lesson 4 of 42

Python Comments

Explain your code with single-line comments and docstrings.

Single-line comments

A comment starts with #. Python ignores everything after it on that line.

Example 1Try it yourself
# This is a comment
print("Hello")  # comments can follow code too
# print("This line will not run")

Output

Hello

Multi-line comments

Python has no special multi-line comment syntax — use # on each line. You'll also see triple-quoted strings (""" ... """): when one is the first statement in a function, class or module it becomes a docstring, which documentation tools and help() can read.

Example 2Try it yourself
def area(width, height):
    """Return the area of a rectangle."""
    return width * height

print(area(3, 4))
print(area.__doc__)

Output

12
Return the area of a rectangle.

Good comments

Comment why something is done, not what the code obviously does. x = x + 1 # add one to x adds nothing; retries += 1 # the API is flaky on cold starts explains intent.

Test yourself

Which character starts a comment in Python?

  1. //
  2. #
  3. --
  4. /*
Show answer

Answer: #