Comments in Python: The Complete Guide to Writing Clean, Documented Code

Comments in Python are pieces of text the interpreter ignores completely. They exist for one audience: humans. When Python reads your file, it skips every comment, so they never affect how your program runs. But for the people who read, maintain, and extend your code, including your future self, comments are often the difference between code that is understandable and code that is a mystery.

This guide walks through every kind of comment Python supports, explains the crucial distinction between comments and docstrings, and shows you the single habit that separates genuinely useful comments from clutter that rots over time. Code examples appear throughout, because the best way to understand comments is to see them in real code.

Key Takeaways
• A comment is text the Python interpreter ignores; it is written for humans, not the machine.
• Single-line comments start with `#`; inline comments place `#` after code on the same line.
• Python has no true block-comment syntax. You either prefix `#` on every line or use a triple-quoted string as a pseudo-block (which is not really a comment).
Docstrings are triple-quoted strings at the top of a module, function, or class. They document purpose and usage and are accessible via `__doc__` and `help()`.
• The most important rule: comment the why, not the what. The code already shows what it does.

What is a comment in Python?

A comment is any text in your source file that the interpreter does not execute. In Python, the most common way to write a comment is with the hash character (`#`). Everything from the `#` to the end of that line is ignored.

“`python

print(“Hello, world!”) # This text after the code is also a comment. “`

When you run the script above, Python prints `Hello, world!` and silently skips both comment fragments. The comments add no behavior. Their only job is to communicate intent, context, or warnings to whoever reads the code.

This is why comments matter so much in real projects. Code tells the computer *how* to do something. Comments, used well, tell the next developer *why* it was done that way.

How do single-line comments work in Python?

A single-line comment begins with `#` and continues to the end of the line. It can occupy its own line or follow code.

“`python

radius = 5 area = 3.14159 * radius ** 2 print(area) “`

You can stack single-line comments to form a short explanation that spans several lines. Each line still needs its own `#`:

“`python

user_input = input(“Enter a command: “).strip().lower() “`

There is no special syntax for a “comment block” here. What looks like a multi-line comment is simply several single-line comments stacked together. We will return to this point shortly, because it trips up developers coming from languages like C, Java, or JavaScript that have dedicated block-comment markers.

What are inline comments and when should you use them?

An inline comment sits on the same line as a statement, after the code. PEP 8, Python’s official style guide, recommends separating inline comments from the code by at least two spaces, and starting the comment with `# ` (hash plus one space).

“`python x = x + 1 # Compensate for the zero-based index timeout = 30 # Seconds; the API rejects anything higher retries = 3 # Matches the gateway’s own retry budget “`

Inline comments are powerful but easy to abuse. Use them sparingly, and only when they add information the code itself cannot convey. An inline comment that merely restates the obvious is noise:

“`python counter = 0 # Set counter to zero <-- adds nothing, delete it ```

Compare that to an inline comment that captures a non-obvious constraint:

“`python buffer_size = 4096 # Must match the kernel page size on this platform “`

The second comment tells you something you could never learn by reading the number alone.

How do you write multi-line comments in Python?

Here is the honest answer that surprises many newcomers: Python has no true multi-line or block comment syntax. There is no `/* … */` equivalent. There are two common approaches, and they are not the same thing.

Approach 1: a hash on every line

The official, idiomatic way to comment several lines is to put a `#` at the start of each line.

“`python

def is_valid_card(number): … “`

This is genuinely a comment. The interpreter ignores every one of those lines.

Approach 2: a triple-quoted string as a pseudo-block

You will sometimes see a triple-quoted string used to “comment out” a block:

“`python “”” This block is a string, not a comment. Python evaluates it, then discards it because nothing assigns it to a variable. “”” print(“The code still runs.”) “`

This works as a pseudo-comment, but it is important to understand the difference. A triple-quoted string is a real string object. Python actually creates it in memory and then throws it away because nothing references it. It is *not* a comment in the technical sense; it just behaves like one when placed where its value is unused.

The two approaches differ in more than syntax. A `#` comment is invisible to the interpreter at every position in your code. A triple-quoted string is only “ignored” when it sits in a statement position where its value is discarded. Put that same triple-quoted string as the first statement of a module, function, or class, and it stops being throwaway text entirely. It becomes a docstring, which is a documented, retrievable part of your program. That single difference in placement is why the next section matters so much.

Comment type Syntax Typical use
Single-line `# comment` A short note on its own line
Inline `code # comment` Clarifying one specific statement
Multi-line (idiomatic) `#` on every line Explaining a block of logic
Pseudo-block (string) `””” … “””` in unused position Quick temporary block-out (not a real comment)
Docstring `””” … “””` as first statement Documenting a module, function, or class

What is a docstring and how is it different from a comment?

A docstring is a triple-quoted string placed as the first statement inside a module, function, class, or method. Unlike a comment, a docstring is not discarded. Python attaches it to the object’s `__doc__` attribute, and tools like `help()` and IDEs read it.

“`python def celsius_to_fahrenheit(celsius): “””Convert a temperature from Celsius to Fahrenheit.

Args: celsius (float): Temperature in degrees Celsius.

Returns: float: Temperature in degrees Fahrenheit. “”” return celsius * 9 / 5 + 32 “`

Because the docstring lives on the object, you can retrieve it at runtime:

“`python print(celsius_to_fahrenheit.__doc__)

help(celsius_to_fahrenheit)

“`

Modules and classes work the same way. The docstring is the first thing inside the block:

“`python “””payments.py — utilities for charging and refunding customers.”””

class PaymentGateway: “””A thin client over the upstream payment provider’s REST API.”””

def charge(self, amount): “””Charge the customer `amount` cents. Returns a transaction ID.””” … “`

The distinction is fundamental. A comment explains the code to a reader looking at the source. A docstring documents the interface to anyone using the object, even without seeing the source, through `help()`, generated documentation, or editor tooltips. Comments are for maintainers; docstrings are for users. Many projects find docstrings add more lasting value than inline comments, because they describe purpose and usage rather than line-by-line mechanics.

If you want to go deeper on writing effective docstrings and following conventions like Google or NumPy style, see .

How do you comment out code in Python?

“Commenting out” means disabling code without deleting it, usually while debugging. You prefix the lines with `#` so the interpreter skips them.

“`python def process(data): cleaned = normalize(data)

return cleaned “`

Most editors let you toggle this on a selection with a keyboard shortcut (often `Ctrl + /`), adding or removing `#` on every selected line at once. Commenting out code is fine as a temporary tactic. It should not survive into committed code; dead commented-out blocks confuse readers and your version control system already remembers the old version.

What are the best practices for comments in Python?

Good commenting is a discipline, not a syntax. These practices, several drawn directly from PEP 8, will keep your comments valuable.

Comment the why, not the what

This is the single rule that separates useful comments from clutter. The code itself already shows *what* it does. Anyone fluent in Python reads `total = price * 1.08` and sees the multiplication. So a comment that says `# multiply price by 1.08` is pure noise, and worse, it will rot the moment that number changes.

“`python

total = price * 1.08 # multiply price by 1.08

total = price * 1.08 # 8% sales tax for the default region; overridden per-locale below “`

The good comment captures information no amount of reading the code reveals: the intent, the reason, the non-obvious constraint. Before writing any comment, ask: *does this explain something the code itself does not already make obvious?* If it just narrates the syntax, delete it. If it captures a why, a gotcha, or a decision, keep it. Good comments are the reasoning behind the code, not a translation of it.

Keep comments updated

A stale comment is worse than no comment, because it actively misleads. If you change the code, change the comment in the same edit. A comment that says “retries 3 times” next to code that now retries 5 is a trap for the next reader.

Do not over-comment obvious code

Trust your reader to know the language. Obvious operations do not need narration.

“`python i = i + 1 # increment i <-- delete; this is obvious ```

Clean, well-named code reduces the need for comments in the first place. A function called `calculate_overdue_fee` needs less explanation than one called `calc`.

Follow PEP 8 comment style

PEP 8 sets a few concrete conventions:

  • Block and inline comments start with `# ` (hash, then a single space).
  • Inline comments are separated from code by at least two spaces.
  • Comments should be complete sentences, with the first word capitalized.
  • Keep comments at the same indentation level as the code they describe.

“`python

def example(): value = compute() # Inline comment, two spaces before the hash return value “`

If you are still solidifying the underlying rules of how Python reads code, indentation, statements, and tokens, a refresher on pairs naturally with good commenting habits. And if comments are part of your first steps with the language, our guide to covers the surrounding fundamentals.

How DarazHost helps you write and run clean Python

Clean, well-commented code deserves an environment you actually control. DarazHost VPS and dedicated servers give developers a real, controllable Python environment: write, document, and run clean, well-commented code on guaranteed resources with full root access. Install any interpreter version, manage your own virtual environments, and run linters and documentation tools without fighting a locked-down shared host. It is the dependable home your Python projects need, backed by 24/7 support so your deployments stay up while you focus on the code.

For the bigger picture on choosing and configuring a developer-grade environment, read our pillar guide, Hosting for Developers: The Complete Guide to a Real Environment You Control. When you are ready to see your commented code in action, walks through execution end to end.

Putting it all together

A well-commented Python file uses each tool for its proper job: docstrings to document the public interface, sparse inline comments to flag non-obvious decisions, and `#` blocks to explain tricky logic.

“`python “””inventory.py — stock-level tracking for the warehouse service.”””

def reorder_point(daily_usage, lead_time_days, safety_stock): “””Calculate the stock level at which to reorder an item.

Args: daily_usage (float): Average units consumed per day. lead_time_days (int): Days between placing and receiving an order. safety_stock (int): Buffer units to cover demand spikes.

Returns: int: The reorder threshold in units. “””

demand_during_lead_time = daily_usage * lead_time_days return round(demand_during_lead_time) + safety_stock “`

Notice what each piece does. The module docstring states the file’s purpose. The function docstring documents the interface for anyone calling it. The `#` block explains a *decision*, why safety stock is an input rather than a calculation, which is exactly the kind of “why” the code cannot express on its own.

Frequently asked questions

Does Python have a multi-line comment syntax like `/* */`? No. Python has no dedicated block-comment syntax. You either prefix `#` on each line (the idiomatic way) or use a triple-quoted string in an unused position as a pseudo-block. The triple-quoted string is technically a string object, not a comment.

What is the difference between a comment and a docstring? A comment (`#`) is ignored entirely by the interpreter and exists only in the source. A docstring is a triple-quoted string placed as the first statement of a module, function, or class; Python stores it in `__doc__` and tools like `help()` can read it at runtime. Comments explain code to maintainers; docstrings document interfaces to users.

How do I comment out multiple lines quickly? Select the lines and use your editor’s toggle-comment shortcut, often `Ctrl + /`, which adds or removes a `#` at the start of each selected line. Avoid leaving commented-out code in committed files.

Why are my comments not showing up when the program runs? That is correct behavior. Comments are never executed or printed; the interpreter ignores them. If you want text to appear at runtime, use `print()` or a logging call instead of a comment.

What is the most important rule for writing good comments? Comment the *why*, not the *what*. The code already shows what it does, so explain the intent, reason, or non-obvious constraint instead. A comment that narrates the syntax is clutter and will go stale; a comment that captures a decision keeps its value.

About the Author

Leave a Reply