Python with AI Tutorial · Chapter 4 of 48
Python comments are notes inside your code that Python ignores when it runs the program. A single-line comment starts with #, a multi-line comment is several # lines or a triple-quoted string, and a docstring is a special string that documents a function or module. Good comments explain why, not what.
Single-line comments with #
Everything from the # symbol to the end of the line is a comment. Python skips it entirely, so comments never change what a program does. Use them to record intent, assumptions or the source of a number.
# GST rate for standard goods in India (as of FY 2026-27)
gst_rate = 0.18
net_price = 2500
print("Price with GST:", net_price * (1 + gst_rate))
Output: Price with GST: 2950.0
Comments are also where you leave a trail for your future self. A script that loads a report usually encodes a dozen small decisions: which sheet to read, which date format to expect, why one column is skipped. Recording those decisions next to the code means nobody has to reverse-engineer them later, and an AI assistant that reads the file gets the same context you had when you wrote it.
Inline comments
A comment can also sit at the end of a line of code. Keep inline comments short, and separate them from the code with at least two spaces, which is the PEP 8 style convention.
salary = 60000
bonus = salary * 0.12 # 12% annual bonus agreed in the offer letter
print("Total package:", salary + bonus)
Output: Total package: 67200.0
Multi-line comments
Python has no dedicated multi-line comment symbol like /* ... */ in other languages. The standard approach is simply a # at the start of each line. VS Code does this for you: select the lines and press Ctrl+/ (Mac: Cmd+/).
# Month-end close checklist
# 1. Import bank statement
# 2. Match invoices to payments
# 3. Flag anything unmatched over 30 days
unmatched = ["INV-1041", "INV-1057"]
print("Unmatched invoices:", len(unmatched))
Output: Unmatched invoices: 2
Some people use a triple-quoted string as a block comment. It works because a string that is not assigned to anything is evaluated and thrown away, but it is technically a string, not a comment, so linters may warn about it.
"""
This block is a string expression, not a true comment.
Python evaluates it and discards it.
"""
print("Still runs normally")
Output: Still runs normally
Docstrings: comments Python can read
A docstring is a triple-quoted string placed as the first statement inside a function, class or module. Unlike a normal comment, Python stores it in the __doc__ attribute, and tools such as VS Code show it as a tooltip when you hover over the function name.
def net_pay(gross, tax_rate):
"""Return take-home pay after deducting tax.
gross: monthly gross salary
tax_rate: decimal, e.g. 0.20 for 20%
"""
return gross - gross * tax_rate
print(net_pay(50000, 0.20))
print(net_pay.__doc__.splitlines()[0])
Output: 40000.0 Return take-home pay after deducting tax.
The built-in help() function prints docstrings too. Try help(net_pay) in the REPL, or help(len) to read the documentation for a built-in function without leaving your terminal.
Docstring conventions matter because tools rely on them. The first line should be a short summary sentence that fits on one line, followed by a blank line and any detail. Popular formats such as Google style and NumPy style add labelled sections for parameters and return values, and VS Code, Copilot and documentation generators all understand them. When you ask an AI assistant to document a function, name the style you want and it will follow it.
| Type | Syntax | Where it goes | Read by Python? |
|---|---|---|---|
| Single-line | # text |
Own line or end of a code line | No, ignored |
| Multi-line | Several # lines |
Above the code it describes | No, ignored |
| String block | """ text """ |
Anywhere a statement can go | Evaluated, then discarded |
| Docstring | """ text """ |
First line inside def, class or module | Yes, stored in __doc__ |
Using comments to disable code
While testing, you often want to switch a line off without deleting it. Commenting it out is the quickest way. Just remember to remove or restore these lines before sharing the script, or they become clutter.
orders = [320, 870, 150]
# orders.append(9999) # test value, disabled
print("Order count:", len(orders))
print("Largest order:", max(orders))
Output: Order count: 3 Largest order: 870
Commenting out is also a safe way to experiment. Comment out the line you suspect is wrong, run the script, and see whether the problem disappears. It is a crude but effective debugging technique that you will refine in the debugging chapter later in the course.
What makes a good comment
A comment that repeats the code adds nothing; a comment that explains a business rule saves the next reader (often you, six months later) real time. Compare the two styles.
# Bad: restates the code
discount = 0.15 # set discount to 0.15
# Good: explains the reason
discount = 0.15 # Loyalty tier 2 customers get 15% (pricing policy, Mar 2026)
print("Discounted:", 1000 * (1 - discount))
Output: Discounted: 850.0
Give the assistant uncommented code and ask it to add comments that explain intent rather than mechanics; then judge whether you agree with each one.
Add helpful comments to this Python code. Do not describe what each line literally does; instead explain the business reason or assumption behind it. Then add a proper docstring to the function:
def late_fee(days_overdue, invoice_amount):
if days_overdue <= 7:
return 0
fee = invoice_amount * 0.02 * (days_overdue // 30 + 1)
return min(fee, invoice_amount * 0.10)
print(late_fee(45, 12000))
Ask the assistant to explain the difference between a docstring and a comment using your own example, and to show how help() uses it.
Explain the difference between a Python comment and a docstring in under 120 words. Then take this function, write a Google-style docstring for it, and show me exactly what help(monthly_payment) would print:
def monthly_payment(principal, annual_rate, months):
r = annual_rate / 12
return principal * r / (1 - (1 + r) ** -months)
Common mistakes
- Writing comments that restate the code (
x = x + 1 # add 1 to x). Explain why, not what. - Letting comments go stale. If you change the code, change the comment, or delete it.
- Putting the docstring anywhere other than the first statement of the function; Python will then treat it as a plain string and
__doc__staysNone. - Using
//or--for comments out of habit from other languages. In Python//is integer division. - Leaving large blocks of commented-out code in a finished script. Use version control (Git) to keep old versions instead.
Exercise
Write a function shipping_cost(weight_kg) that returns 50 for parcels up to 2 kg and 50 plus 20 per additional kilogram above that. Add a docstring and one comment that explains the pricing rule. Print the cost for a 5 kg parcel and print the first line of the docstring.
Show answer
def shipping_cost(weight_kg):
"""Return the shipping charge for a parcel in rupees."""
base = 50
if weight_kg <= 2:
return base
# Courier contract: flat 50 up to 2 kg, then 20 per extra kg
return base + (weight_kg - 2) * 20
print(shipping_cost(5))
print(shipping_cost.__doc__)
Output: 110 Return the shipping charge for a parcel in rupees.
Related chapters
FAQ
How do I write a multi-line comment in Python?
Start each line with #. Python has no block-comment symbol. In VS Code, select the lines and press Ctrl+/ to comment or uncomment them all at once.
What is the difference between a comment and a docstring?
A comment starting with # is discarded by Python. A docstring is a triple-quoted string as the first statement in a function, class or module; Python keeps it in __doc__ and help() displays it.
Do comments slow down a Python program?
No. Comments are removed when Python compiles the file to bytecode, so they have no effect on speed. Docstrings are kept but the cost is negligible.
Working with spreadsheets too? Ready-made Excel, Google Sheets and Power BI templates are at NextGenTemplates.com.
Chapter 4 of 48 · Python with AI: all 48 chapters



