By WebNest Studio Engineering Team
Python Tutorial
Comments and Docstrings in Python
Code is read far more often than it is written. Comments explain why code does something non-obvious, and docstrings document what modules, functions and classes do — and, unlike comments, they are available at runtime through help() and used by IDEs and documentation generators.
This lesson covers single-line and "multi-line" comments, docstring conventions for functions and classes, and how to write comments that help rather than clutter.
Why it matters
Code is read far more often than it is written, often by you some months later. A comment that explains why something is done saves that reader from working it out again, and a docstring is what an editor shows when someone hovers over your function. Both are part of writing code that other people can use.
Comments
A comment starts with # and runs to the end of the line; Python ignores it. Python has no special multi-line comment syntax — use several # lines. (A bare triple-quoted string is sometimes used, but it is really a string expression, not a comment.) Inline comments should be separated from code by at least two spaces.
Docstrings
A docstring is a string literal that is the first statement of a module, function, class or method. It is stored in the object's __doc__ attribute and shown by help(). Use triple double quotes. The first line is a short summary; longer docstrings describe arguments, return values and exceptions — common styles are Google style and NumPy style.
Writing Good Comments
Explain intent, business rules and surprising decisions ("Tax is rounded per item, as required by GST rules"), not what the code obviously does ("increment i"). Keep comments updated — a wrong comment is worse than none. Prefer clear names and small functions over explaining unclear code with comments.
Examples
Single-line, inline and block comments
# Calculate the final price after discount and GST
price = 1000
discount = 0.10 # 10% festival discount
# GST is applied after the discount,
# as required on the invoice.
final_price = price * (1 - discount) * 1.18
print(round(final_price, 2))
1062.0
Function and class docstrings, read with help() and __doc__
def bmi(weight_kg, height_m):
"""Return the body-mass index.
Args:
weight_kg: Weight in kilograms.
height_m: Height in metres.
Returns:
The BMI rounded to one decimal place.
"""
return round(weight_kg / height_m ** 2, 1)
class Student:
"""A learner enrolled on the Webnest platform."""
print(bmi(68, 1.75))
print(bmi.__doc__.splitlines()[0])
print(Student.__doc__)
22.2
Return the body-mass index.
A learner enrolled on the Webnest platform.
Common Mistakes
- Commenting every line with what the code already says.
- Leaving outdated comments after changing the code.
- Using triple-quoted strings everywhere as "comments" instead of #.
- Skipping docstrings on public functions and classes that others will use.
Exercise
Add a docstring to the function so that the first print shows it, and complete the function so that the second print shows the area.
Expected output: Return the area of a rectangle. then 12
def area(width, height):
# TODO: add the docstring "Return the area of a rectangle."
# TODO: return the area
pass
print(area.__doc__)
print(area(3, 4))
Show hints
- A docstring is a string written as the first statement inside the function, usually in triple quotes.
- A comment starting with
#is not a docstring and is not stored in__doc__.
Show solution
def area(width, height):
"""Return the area of a rectangle."""
return width * height
print(area.__doc__)
print(area(3, 4))
Quick quiz
1. Where does Python store the docstring of a function?
- A. In a separate file
- B. In the __name__ attribute
- C. It is discarded
- D. In the function's __doc__ attribute
Show answer
D. help() and editors read the text from __doc__.
2. How is a comment spanning several lines normally written?
- A. With a # at the start of each line
- B. Between /* and */
- C. Between <!-- and -->
- D. With // on each line
Show answer
A. Python has no block-comment syntax. Each line starts with #.
3. Which comment is the most useful?
- A. # add 1 to i
- B. # retry three times because the payment API sometimes times out
- C. # loop over the list
- D. # this is a variable
Show answer
B. It gives the reason, which cannot be read from the code. The others repeat what the code already says.
Interview questions
What is the difference between a comment and a docstring?
Show answer
A comment starts with #, is ignored by the interpreter, and is for people reading the source. A docstring is a string placed as the first statement of a module, class or function. Python keeps it in the object's __doc__ attribute, so it is available at runtime to help(), editors and documentation generators.
How can you read the documentation of a function from within Python?
Show answer
Call help(function), which prints the signature and the docstring, or read function.__doc__ directly. In the REPL this is the quickest way to check how a built-in or library function is used.
Key Points to Remember
- # starts a comment; use several # lines for multi-line comments.
- Docstrings are the first string in a module, function or class, stored in __doc__.
- help(obj) and IDEs display docstrings.
- Comment the why, not the what; keep comments accurate.
Practice in the playground
Write and run your own code for this topic, or start from the exercise or an example. Runs Python in your browser. Your code for each topic is kept in this browser.
Run the examples
Change an input, predict the result, then compare it with the output. Explain why the result changes.
Written by
WebNest Studio Engineering Team
Practical lessons from developers working with Java, Python, React, databases and production systems.
Led by Vansh Duggal, Founder, WebNest Studio · Full-stack & software engineering