iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

Python Comments

Python ignores everything after a # on a line. There's no block-comment syntax; for multi-line comments most code uses a triple-quoted string.

Single line

PYTHON
# Calculate the discount percentage
discount = price * 0.10
total = price - discount   # apply it

"Block" comment

PYTHON
"""
This module loads orders from CSV
and uploads them to the warehouse API.
Owner: @ada
"""

def upload(): ...

Docstrings

A triple-quoted string as the first statement of a module, function, class, or method becomes its docstring — readable from help(obj) and tools like Sphinx:

PYTHON
def discount(price: float, pct: float) -> float:
    """Return `price` reduced by `pct` percent."""
    return price * (1 - pct / 100)

help(discount)

Comments that earn their place

  • Why, not what — the code already shows what.
  • Non-obvious algorithms, business rules, workarounds.
  • "TODO:" / "FIXME:" markers — most editors highlight them.
Tip: Comments rot — code changes, comments don't. The lower-maintenance alternative is to extract a well-named function. apply_loyalty_discount(price) often beats # apply loyalty discount.

Example

Example
# This is a single-line comment
"""
This is a
multi-line docstring used as a block comment.
"""
print('after comments')
Try it Yourself »

Exercise

Start a single-line comment with…

this is a comment

Test yourself

Q1. A single-line comment starts with…
Q2. "Block" comments commonly use…
Q3. A docstring is…

Discussion

Loading…