Thuta Learning
Python
BasicProgrammingBeginner

Python Comments

PythonLesson 520 min

What you'll walk away with

  • Write # comments and inline comments
  • Write a docstring for a function and show how __doc__ and help() read it
  • Tell when a triple-quoted string is a docstring and when it is not
  • Distinguish comments that repeat "what" from comments that explain "why"

Explain it simply

Explain it simply

A comment is a note left in the code for human readers. In Python, the interpreter ignores everything after a #, so comments never change what the program does. They are like pencil notes in the margin of a book: the text stays the same, but the next reader gets help.

That next reader is often you, six months later. The code itself can tell you what happens, but only a comment can tell you why it was done that way.

Problem → Why → Solution

The problem: a comment that contradicts the code

In the code below the comment says 10% but the code takes off 15%. Someone changed the discount and never updated the comment, and the next developer trusted the comment and reported 10% in a finance summary. The comment on line 4 is useless in a different way: it just repeats the code in words.

checkout.py
price = 20000

# Apply a 10% member discount
price = price * 0.85
count = count + 1   # add 1 to count

Why are these comments harmful?

Python never checks comments, so when code and comment disagree, no error tells you. A comment that restates the code adds reading time and creates a second place to update whenever the code changes. A good comment records only what the code cannot say, such as why the factor is 0.85 or who decided it.

Core concept: three kinds of notes and their jobs

A single-line comment starts with # and runs to the end of the line. It can fill a whole line or sit after code as an inline comment; PEP 8 recommends at least two spaces between the code and the #. Python has no separate multi-line comment syntax like /* ... */, so to comment out several lines you put # in front of each one; most editors do this for a selection with Ctrl+/.

A docstring is not a comment. It is a string literal, usually written with """...""", placed as the very first statement of a module, function or class. Python keeps it in the __doc__ attribute, so help(function_name), editor hover tooltips and documentation tools can display it. The convention is a one-sentence summary on the first line, then a blank line and more detail if needed.

Be careful: a triple-quoted string in the middle of code is not a docstring. Python reads it as a value and throws it away without storing it, so it seems to behave like a comment, but it is not one. You may see it called a "multi-line comment" elsewhere; PEP 8 recommends writing block comments with # instead.

KindSyntaxUsed for
Single-line comment# noteExplaining why the next block works as it does
Inline commentcode # noteExplaining one surprising line
Block comment# at the start of each lineLonger explanations, or switching code off for a while
Docstring"""Summary.""" (first statement)Documenting a module, function or class; help() reads it

The rule for good comments is simple: let the code say what, and let the comment say why. Clear names like total_with_tax and type hints like def area(width: float) -> float make many comments unnecessary. When you leave a TODO, state exactly what is missing and why.

A few comments are written for tools rather than people. If a file's first line is #!/usr/bin/env python3 (a shebang), macOS and Linux know which interpreter to use when you run ./script.py directly. # noqa tells a linter to skip that line, and # type: ignore tells a type checker the same. In Python 3, source files are UTF-8 by default, so you no longer need a # -*- coding: utf-8 -*- line to write comments in Myanmar.

Mental model: who reads which note
  1. # comment: developers reading code
  2. Docstring: people calling the function
  3. Names and hints: the code itself
  4. Interpreter: skips every # note

A docstring survives as data inside the running program; a # comment exists only in the source file.

General pattern: comments and docstrings

python
# A full-line comment explains the next block.
value = compute()  # an inline comment: two spaces before #


def function_name(param):
    """One-line summary of what the function returns.

    Optional details: rules, units, edge cases.
    """
    ...

Put a # comment above or beside the code it explains. A docstring goes immediately under the def line, at the same indentation as the body.

Example: comments that explain why

This function calculates a delivery fee. The docstring explains the pricing rule to anyone who calls the function, while the # comment explains why math.ceil was chosen. Notice that the disabled line also says why it is switched off.

shipping.py
import math

BASE_LIMIT_KG = 1.0


def shipping_fee(weight_kg: float) -> int:
    """Return the delivery fee in kyat for a parcel.

    The first kilogram costs the base rate. Every started
    kilogram after that adds 500 kyat, so 2.3 kg pays for 3.
    """
    base = 2000
    if weight_kg <= BASE_LIMIT_KG:
        return base
    # ceil, not round: the courier charges 1.2 kg as 2 kg
    return base + (math.ceil(weight_kg) - 1) * 500


print(shipping_fee(0.8))
print(shipping_fee(2.3))
# print(shipping_fee(-1))  # disabled until negative weights are rejected
print(shipping_fee.__doc__.splitlines()[0])

Code breakdown

  1. Lines 7-11 """Return the delivery fee in kyat for a parcel.

    It is the first statement under the def line, so it is the docstring. The first line is a one-sentence summary; the rest explains the rule and the units (kyat, kg).

  2. Line 15 # ceil, not round: the courier charges 1.2 kg as 2 kg

    Reading the code shows math.ceil, but not why round() was rejected. This comment records that decision, which stops someone from "fixing" it to round() later.

  3. Line 21# print(shipping_fee(-1)) # disabled until negative weights are rejected

    The leading # switches the call off temporarily, and the trailing note says why and when it can come back.

  4. Line 22print(shipping_fee.__doc__.splitlines()[0])

    This proves the docstring exists at runtime in __doc__; splitlines()[0] keeps only its first line. There is no way to read a # comment back like this.

You should see
2000
3000
Return the delivery fee in kyat for a parcel.

Rewriting code so it needs no comment

Whenever you feel a comment is needed, first ask whether a better name would make it unnecessary. The two versions below do the same work, but in the second one a constant names the magic number and the function name describes the result, so no comment is required.

names_over_comments.py
# Before: the comment carries the meaning
d = 7 * 24 * 60  # minutes in a week
print(d)

# After: the names carry the meaning
MINUTES_PER_WEEK = 7 * 24 * 60


def minutes_to_weeks(minutes: int) -> float:
    return minutes / MINUTES_PER_WEEK


print(minutes_to_weeks(20160))

In real projects

Where this shows up in real projects

Most library documentation websites are generated from docstrings: tools such as Sphinx read each function's docstring and build web pages from it. The explanation that pops up when you hover over a function in VS Code is the docstring too. Writing docstrings for public functions is a gift to everyone else on the team.

In code review, reviewers ask for comments that restate the code to be deleted, and for an explanation wherever unusual code has no reason given. They also ask for commented-out code to be removed, because git history keeps it if anyone needs it back. When fixing a bug, adding the ticket number to a comment helps people trace later why the code looks the way it does.

Common mistakes

Common mistakes

1. Changing code but not its comment

As in the 10% versus 0.85 example, a stale comment is worse than none because people believe it. Every time you edit a line, reread the comment above it and check it is still true; delete it if it no longer helps.

2. Putting the docstring in the wrong place

Writing it as a # comment above the def line, or as a string after other statements in the body, leaves __doc__ as None and help() shows nothing. The first line under the def must be the """ string.

3. Piling up commented-out code

Lines like # x = 10 linger until nobody remembers why they are there, and they clutter the file. Delete them once your experiment is over, and if one must stay for a while, say why next to it.

Best practices

Best practices

  • Give every public function and class a docstring whose first line is a complete sentence ending in a full stop.
  • Mention units (kg, kyat, seconds) and what happens with invalid input in the docstring.
  • Place a comment directly above the code it explains, at the same indentation.
  • Make TODOs specific, for example "TODO: validate negative weights before release".

Mini challenge

Mini challenge: document an average-speed function

Write a function that turns a distance in km and a time in minutes into an average speed in km/h, with a proper docstring and one comment that explains why.

  • The docstring's first line is a one-sentence summary that mentions the units
  • The line converting minutes to hours has a comment saying why it divides by 60
  • Print average_speed(30, 45) with one decimal place
  • Print the first line of the docstring from __doc__
speed.py
def average_speed(distance_km: float, minutes: float) -> float:
    # TODO: write a docstring - summary line first, mention km and minutes
    # TODO: convert minutes to hours (comment: why?)
    # TODO: return distance divided by hours
    ...


# TODO: print the speed for 30 km in 45 minutes, e.g. "40.0 km/h"
# TODO: print the first line of average_speed.__doc__

Expected: Expected output: 40.0 km/h Return the average speed in km/h for a trip.

Show hint

f"{value:.1f}" shows one decimal place, and __doc__.splitlines()[0] is the docstring's first line.

Show solution
speed.py
def average_speed(distance_km: float, minutes: float) -> float:
    """Return the average speed in km/h for a trip.

    distance_km is the trip length in kilometres and minutes
    is the travel time; both must be positive.
    """
    # speeds are quoted per hour, but trip logs record minutes
    hours = minutes / 60
    return distance_km / hours


speed = average_speed(30, 45)
print(f"{speed:.1f} km/h")
print(average_speed.__doc__.splitlines()[0])

Quick quiz 1 / 3

Under def f(): the first line is # adds one and the next is return 1. What does print(f.__doc__) show?

Quick quiz 2 / 3

Which comment is the most useful?

Quick quiz 3 / 3

A file contains only the line """Note""" followed by print("A") # print("B"). What is the output?

What to remember

  • The interpreter skips everything after #; leave two spaces before an inline comment.
  • A docstring is the string that opens a module, function or class, read by __doc__ and help().
  • A triple-quoted string in the middle of code is neither a docstring nor real comment syntax.
  • Let comments explain why, and let good names and type hints say what.
  • Check the comments whenever you change code; a stale comment is worse than none.

The Python Tutorial — Python Software Foundation

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

Python Comments | Thuta Learning