VMware ESXi and vSphere Cluster Management

How to Write Comments in Python

Learn how to write Python comments with #, create multi-line explanations, use docstrings correctly, and understand what Python executes or ignores.

Comments are notes in source code written for people, not instructions intended to produce normal program behavior. They help you and other programmers understand why code exists, what assumptions it makes, and how it should be used.

This lesson covers the hash character (#), full-line and inline comments, multi-line explanations, and the difference between comments and docstrings.

What Is a Comment?

A comment is non-executable text written for programmers who read or maintain code. The Python interpreter is the runtime that reads and executes Python source code. When it encounters a comment, it ignores the comment text for execution.

Comments commonly help you:

  • Clarify the intent of a section of code.
  • Record an assumption, such as the expected units of a value.
  • Explain a non-obvious design or implementation decision.
  • Temporarily disable a statement while developing or debugging.

A useful comment usually explains why code exists or how it should be used. It should not merely restate an obvious instruction. For example, total = price + tax is already clear, so a comment saying “add price and tax” adds little value. A comment explaining that tax is calculated before a discount might be useful if that decision is not obvious.

How Python Separates Comments from Code

A Python source file can contain executable statements and explanatory text. The hash character, also called the number sign, is Python's comment marker. Text after # on the same physical line is ignored by the interpreter.

# This line is a comment.
print("Python executes this statement.")  # This part is also a comment.

The program produces:

Python executes this statement.

The comments do not appear in the output and do not change what the print() call does.

Single-Line Comments with #

Full-line comments

A full-line comment occupies its own line. Place it near the code it describes, usually immediately above that code.

# Print a greeting for the user
print("Hello, world!")

Only the print() call runs, so the output is:

Hello, world!

Inline comments

An inline comment appears after executable code on the same line.

print("Hello, world!")  # Display a greeting

Python executes the call and ignores everything after the #. Inline comments are useful when a short explanation adds important context, but long explanations should normally be moved to a separate line.

Where the comment ends

Everything after # on that physical line belongs to the comment. However, a # inside a quoted string is string content, not a comment marker.

print("Use # to begin a Python comment")

This prints:

Use # to begin a Python comment

The hash character is printed because it is inside the string literal. A string literal is text enclosed in quotation marks that represents a Python string value.

Commenting a First Python Program

Here is a small program with both a leading comment and an inline comment:

# This program displays a greeting for the user.
print("Hello, world!")  # Display the greeting

The interpreter ignores both comments and executes only the print() statement. The expected console output is:

Hello, world!

Comments do not generate normal program output.

Multi-Line Explanatory Text

Python does not have a separate block-comment delimiter comparable to the block-comment syntax found in some other languages. For an ordinary multi-line comment, write several consecutive lines and begin each line with #.

# This program displays a greeting.
# It is intended as a first Python example.
# The greeting is written directly to the console.
print("Hello, world!")

This style is often called a block comment: a multi-line explanation written as consecutive comment lines. Each line is independently recognized as a comment, and only the print statement has visible runtime behavior.

Triple-Quoted Strings and Docstrings

Triple single quotes (''') and triple double quotes (""") create triple-quoted strings. A triple-quoted string is a string literal enclosed by three matching quote characters and can span multiple lines.

"""This is a multi-line string."""

'''This is another multi-line string.'''

Triple-quoted strings are not general-purpose comments. An unassigned triple-quoted string may appear to behave like a comment because its value is not used:

"""
This text is a string expression.
It is not a # comment.
"""

print("Done")

The string expression does not produce normal output here, but Python still treats it as a string expression. It can use memory and may be processed differently by tools. Use consecutive # lines for ordinary explanatory comments.

Docstrings

A docstring is a triple-quoted string used as documentation when it is the first statement in a module, function, class, or method. Python preserves it so documentation tools and programs can inspect it through the __doc__ attribute.

def greet(name):
    """Return a personalized greeting."""
    return f"Hello, {name}!"

print(greet.__doc__)

The output is:

Return a personalized greeting.

Because the triple-quoted string is the first statement in greet(), it becomes that function's docstring. A triple-quoted string placed elsewhere is simply a string expression, not the documentation for the surrounding function or class.

Python comments and documentation strings

Construct: # comment
Typical syntax: # Explain the purpose
Actual comment? Yes
Primary purpose: Human-readable source notes
Available at runtime? No

Construct: Consecutive # comment lines
Typical syntax: One # marker on each line
Actual comment? Yes
Primary purpose: Ordinary multi-line explanation
Available at runtime? No

Construct: Triple-quoted unassigned string
Typical syntax: """text"""
Actual comment? No; it is a string expression
Primary purpose: A string value, if intentionally used
Available at runtime? It is part of the program's expressions, but has no useful reference when unassigned

Construct: Triple-quoted docstring
Typical syntax: First statement inside a function, class, method, or module
Actual comment? No; it is a string literal used as documentation
Primary purpose: Document a program element
Available at runtime? Yes, through __doc__ and documentation tools

Comment Placement Examples

Placement: Full-line comment
Example pattern: # Explain the next statement
When to use it: To describe a nearby statement or section

Placement: Inline comment
Example pattern: timeout = 30 # seconds
When to use it: For short, important context that fits clearly on the line

Placement: Multi-line block comment
Example pattern: Several lines, each beginning with #
When to use it: For a longer explanation of an algorithm, assumption, or decision

Placement: Function or class docstring
Example pattern: A triple-quoted string as the first statement
When to use it: To publish documentation that users and tools can inspect

Good Comment-Writing Practices

  • Write complete, concise explanations.
  • Keep comments close to the code they explain.
  • Keep comments current when the code changes. An outdated comment can mislead readers.
  • Prefer descriptive variable and function names when a name can make a comment unnecessary.
  • Use inline comments sparingly so lines remain readable.
  • Avoid leaving commented-out dead code in final code. Remove obsolete code or use version control to recover earlier versions.
  • Explain non-obvious reasons and constraints rather than repeating what obvious code does.

Common Python style guidance recommends a space after the hash in normal comments, such as # Calculate the total. Place block comments near the relevant code and use inline comments only when they add useful context. Use docstrings for public modules, functions, classes, and methods that need runtime-accessible documentation. These conventions are commonly associated with Python's PEP 8 style guidance.

Running Code That Contains Comments

Save this example as hello.py:

# A first program with a comment
print("Hello, world!")  # Show the greeting

Run it from a terminal with either command, depending on how Python is installed on your system:

python hello.py
python3 hello.py

Expected output:

Hello, world!

You can also test short examples in the interactive interpreter:

python
python3

At the prompt, try a comment followed by a statement:

# Python ignores this line
print("The statement runs")

Troubleshooting Comments

Explanatory text causes a SyntaxError

If text intended as a comment is executed and causes a SyntaxError, it probably does not begin with # and is not valid Python code. Add # before ordinary explanatory text, or make it a correctly positioned docstring when it documents a module, class, or function.

A triple-quoted note has unexpected effects

Triple quotes create a string literal rather than a true comment. The string may be a docstring if it is in the correct first-statement position, or an unnecessary expression elsewhere. Use consecutive # lines for ordinary comments and triple quotes only for intended strings or docstrings.

An inline comment makes a line hard to read

The code and explanation may be too long for one line. Move the explanation to a full-line comment above the relevant statement.

A hash character unexpectedly ends code

Python treats # outside quotation marks as the start of a comment. If the character is meant to be displayed as text, put it inside a quoted string:

message = "The # symbol is part of this message"
print(message)

A comment no longer matches the code

This usually happens when code changes without its documentation being updated. Revise or remove the outdated comment, and favor clear names that reduce the explanatory burden.

Key Points

  • Python uses # for comments.
  • Text after # is ignored through the end of that physical line, unless the hash is inside a string literal.
  • Full-line comments go above the code they explain; inline comments follow code on the same line.
  • Use one # on each line for ordinary multi-line comments.
  • Triple-quoted text is a string, not a general-purpose comment.
  • Use a triple-quoted string as the first statement of a module, function, class, or method when you need a docstring.
  • Good comments explain intent, assumptions, and non-obvious decisions while staying accurate and readable.

Continue practicing with Python comments by adding explanations to short programs and checking that only executable statements affect their output.