Python Notes
How to write comments in Python — single-line, multi-line, docstrings, and best practices to make code readable and maintainable.
Comments are text that Python ignores — they are only for the programmer, not the machine. Just as you write notes in a notebook, you write comments in code so that it makes sense later.
2. Single-Line Comments (#)
The # (hash / pound) symbol creates a single-line comment.
#creates a single-line comment. Everything after#is ignored by Python.
# This is a single-line comment
print("Hello, World!") # This is an inline comment
# You can use comments to explain variables
age = 25 # age in years
salary = 50000 # monthly salary in INR
tax_rate = 0.10 # 10% income taxHello, World!
Comment Position Styles
3. Multi-Line Comments
Python has no official multi-line comment syntax. There are two approaches:
Approach 1: Multiple # Lines (Recommended)
# This is a multi-line comment
# written using multiple hash symbols.
# Each line starts with a # character.
# This is the PEP 8 recommended approach.
def calculate_bmi(weight, height):
# Body Mass Index formula:
# BMI = weight(kg) / height(m)^2
# Normal range: 18.5 - 24.9
bmi = weight / (height ** 2)
return round(bmi, 2)
print(calculate_bmi(70, 1.75))22.86
Approach 2: Triple-Quoted String (Unofficial)
"""
This is a triple-quoted string.
It spans multiple lines.
Python doesn't execute it, so it acts like a comment.
But officially, it's a string object, not a comment!
"""
x = 10
print(x)10
You can write multi-line comment-like text with triple quotes, but technically it's a string object. Using multiple # for real multi-line comments is better practice.Comparison Table
| Feature | # Comment | Triple-Quote String |
|---|---|---|
| Official comment | ✅ Yes | ❌ No (it's a string) |
| Memory usage | None | Creates string object |
| PEP 8 recommended | ✅ Yes | ❌ Not for comments |
| Used as docstring | ❌ No | ✅ Yes (first statement) |
| Syntax highlighting | ✅ Grayed out | Depends on editor |
4. Docstrings — Documentation Strings
A docstring is a special string literal placed as the first statement of a module, function, class, or method.
A Docstring is a special string written at the beginning of a function, class, or module — it serves as official documentation accessible viahelp()and__doc__.
Function Docstring
def greet(name, language="en"):
"""
Greet a person in the specified language.
Parameters:
name (str): The person's name
language (str): Language code — 'en' for English, 'hi' for Hindi
Returns:
str: Greeting message
Example:
>>> greet("Rahul")
'Hello, Rahul!'
>>> greet("Rahul", "hi")
'Namaste, Rahul!'
"""
if language == "hi":
return f"Namaste, {name}!"
return f"Hello, {name}!"
# Access docstring
print(greet("Rahul"))
print(greet("Rahul", "hi"))
print("\n--- Docstring ---")
print(greet.__doc__)Hello, Rahul!
Namaste, Rahul!
--- Docstring ---
Greet a person in the specified language.
Parameters:
name (str): The person's name
language (str): Language code — 'en' for English, 'hi' for Hindi
Returns:
str: Greeting message
Example:
>>> greet("Rahul")
'Hello, Rahul!'
>>> greet("Rahul", "hi")
'Namaste, Rahul!'
Class Docstring
[101] Priya Sharma — Grade: 10th
--- Class Doc ---
Represents a student in the school management system.
...Module Docstring
"""
school_utils.py
===============
Utility functions for the school management system.
Author: WoHoTech
Version: 1.0.0
Date: 2026-06-12
"""
# Module-level constant
SCHOOL_NAME = "WoHo Academy"
def get_school_name():
"""Return the school name."""
return SCHOOL_NAME
# Access module docstring
print(__doc__)5. Using help() with Docstrings
Help on function calculate_compound_interest in module __main__:
calculate_compound_interest(principal, rate, time, n=1)
Calculate compound interest.
Formula: A = P(1 + r/n)^(nt)
Args:
principal (float): Initial investment amount
...6. Special Comments
Shebang Line (Unix/Linux)
#!/usr/bin/env python3
# This tells the OS to run this script with Python 3
print("Running with Python 3")Encoding Declaration
# -*- coding: utf-8 -*-
# This is needed for non-ASCII characters in Python 2
# Python 3 defaults to UTF-8, but good practice to include
name = "रहुल" # Hindi text
print(name)रहुल
TODO / FIXME / NOTE Comments
def process_payment(amount):
# TODO: Add currency conversion support
# FIXME: This doesn't handle negative amounts
# NOTE: Tax rate hardcoded — should come from config
# HACK: Temporary fix until payment API is updated
# OPTIMIZE: This loop runs O(n²) — needs improvement
tax = amount * 0.18 # 18% GST
total = amount + tax
return total
result = process_payment(1000)
print(f"Total: ₹{result}")Total: ₹1180.0
7. Commenting Out Code (Debugging)
def calculate(x, y):
result = x + y
# Debug: print intermediate values
# print(f"x = {x}, y = {y}")
# print(f"Before multiplication: {result}")
result = result * 2
return result
print(calculate(5, 3))16
When you want to temporarily disable some code during debugging, add #. This is called "commenting out" — don't delete it, you might need it later!8. Docstring Formats/Styles
Different teams use different docstring formats:
Google Style (Most Popular)
def divide(a, b):
"""Divide two numbers.
Args:
a (float): Numerator
b (float): Denominator
Returns:
float: Result of a divided by b
Raises:
ZeroDivisionError: If b is zero
Example:
>>> divide(10, 2)
5.0
"""
if b == 0:
raise ZeroDivisionError("Cannot divide by zero!")
return a / b
print(divide(10, 2))
print(divide(15, 3))5.0 5.0
NumPy Style
def add_numbers(a, b):
"""
Add two numbers together.
Parameters
----------
a : int or float
First number
b : int or float
Second number
Returns
-------
int or float
Sum of a and b
"""
return a + breStructuredText Style (Sphinx)
def multiply(a, b):
"""
Multiply two numbers.
:param a: First number
:type a: int or float
:param b: Second number
:type b: int or float
:return: Product of a and b
:rtype: int or float
"""
return a * b9. ASCII Diagram — Comment Types
| │ # -*- coding | utf-8 -*- ◄── Encoding |
| │ # TODO | improve later ◄── Special |
| │ # FIXME | bug here Marker |
10. Best Practices Summary
✅ DO These
Found at index: 3
❌ AVOID These
# ❌ Bad: Stating the obvious
x = x + 1 # add 1 to x — unnecessary!
# ❌ Bad: Outdated comment
# Calculate tax at 10% ← comment says 10% but code does 18%!
tax = price * 0.18
# ❌ Bad: Commented-out code left forever
# old_function()
# another_old_call()
# yet_another()
# (clean up — use git for history instead)Practice Exercises
Exercise 1 — Add Comments to Code
Add meaningful comments to this code:
Exercise 2 — Write Docstrings
Write a function calculate_grade(marks) that:
- Takes marks (0-100) as input
- Returns grade: A(90+), B(75+), C(60+), D(45+), F(below 45)
- Has a complete Google-style docstring with examples
Exercise 3 — Module Documentation
Create a simple Python file calculator.py with:
- Module-level docstring
- 4 functions (add, subtract, multiply, divide)
- Each function has a docstring
- Proper inline comments where needed
Interview Questions
Q1. What is the difference between a comment and a docstring in Python? > A comment starts with # and is completely ignored by Python — no memory allocation. A docstring is a string literal (using triple quotes) placed as the first statement of a function/class/module. It IS stored in the __doc__ attribute and accessible via help().
Q2. How do you write multi-line comments in Python? > Python has no official multi-line comment syntax. You can use multiple # lines (PEP 8 recommended) or triple-quoted strings (unofficial but common). For documentation purposes, use proper docstrings with triple quotes.
Q3. What is a docstring and how do you access it? > A docstring is a string literal placed as the first statement in a module, function, class, or method. Access it via function.__doc__ attribute or help(function). It follows PEP 257 conventions.
Q4. What special comment markers do professional developers use? > Common markers: TODO: (tasks to complete), FIXME: (known bugs), NOTE: (important information), HACK: (temporary workaround), OPTIMIZE: (performance improvements needed), DEPRECATED: (should not be used).
Q5. Why shouldn't you comment obvious code? > Comments should explain WHY code does something, not WHAT it does. Over-commenting adds noise and must be maintained. Good code should be self-documenting through clear variable/function names. Comments become outdated and misleading if not updated with code changes.
⚠️ Common Mistakes
Mistake 1: Obvious Comments Likhna 🙄
# ❌ Bad — this is already obvious from reading the code
x = 10 # assigned 10 to x
name = "Rahul" # stored Rahul in name variable
# ✅ Good — explain WHY, not WHAT
x = 10 # max retry attempts before timeout
name = "Rahul" # default admin user for testingIf a comment merely repeats what the code does, it's unnecessary. Write "why" in comments, not "what"!
Mistake 2: Not Updating Comments 🕸️
# ❌ Bad — comment says 10% but code does 18%
# Apply 10% discount
discount = price * 0.18
# ✅ Good — comment matches the code
# Apply 18% GST tax
tax = price * 0.18When you change code, update the comments too. Outdated comments are misleading — they can be more dangerous than bugs!
Mistake 3: Commented Code Permanently Chhod Dena 🗑️
# ❌ Bad — purana code permanently commented
# result = old_calculation(x, y)
# temp = result * 2
# print(temp)
result = new_calculation(x, y)
# ✅ Good — use Git for history, keep code clean
result = new_calculation(x, y)Use Git version control! Commented-out code makes the codebase dirty. If you need it in the future, you can retrieve it from git history.
Mistake 4: Triple Quotes Ko Comment Samajhna 🤔
# ❌ Bad — this is not a comment, it's a string object (uses memory)
"""
This is not really a comment.
Python creates a string object for this.
"""
# ✅ Good — real multi-line comment
# This is a proper multi-line comment
# Python completely ignores these lines
# No memory allocation happensTriple-quoted strings are actual string objects stored in memory. Real comments are only created with #. Except for docstrings, don't use triple quotes as comments — it wastes memory.Mistake 5: Incorrect Placement of Docstrings 📍
# ❌ Bad — docstring must be FIRST statement
def greet(name):
x = 10
"""This won't be accessible as __doc__"""
return f"Hello, {name}"
# ✅ Good — docstring as first statement
def greet(name):
"""Greet a person by name and return the message."""
x = 10
return f"Hello, {name}"A docstring must always be the first statement inside a function/class. If written elsewhere,__doc__andhelp()won't work!
Mistake 6: Inline Comments Mein No Space 🔤
# ❌ Bad — hard to read, PEP 8 violation
x = 10#this is bad
y = 20 #this is also bad
# ✅ Good — 2 spaces before #, 1 space after #
x = 10 # max connections allowed
y = 20 # timeout in secondsPEP 8 says: put at least 2 spaces before an inline comment, and 1 space after #. Readability matters!Mistake 7: Comments Mein Secret Information 🔒
# ❌ NEVER DO THIS — passwords/keys in comments
# API Key: sk-abc123xyz (for production)
# DB Password: admin@123
# ✅ Good — use environment variables
# API key loaded from .env file (see .env.example for format)
import os
api_key = os.getenv("API_KEY")Never write passwords, API keys, or sensitive data in comments! These can be publicly visible in code repositories. Use environment variables or secret managers instead.
✅ Key Takeaways
- 📝 Comments are created with
#— Python completely ignores them, no memory is used. - 📖 Docstrings are created with triple quotes (
"""...""") — written as the first statement and accessible via__doc__/help(). - 🎯 Explain WHY, not WHAT — write the reason for the logic in comments, not a translation of the code.
- 🔄 Update comments along with code — outdated comments are more dangerous than bugs.
- 📋 Follow PEP 8 — 2 spaces before inline comments, 1 space after
#. - 📚 Follow PEP 257 for docstrings — choose Google Style, NumPy Style, or reStructuredText Style and be consistent.
- 🏷️ Use special markers —
TODO:,FIXME:,NOTE:,HACK:,OPTIMIZE:are helpful for team collaboration. - 🚫 Don't leave commented-out code permanently — use Git for history, keep the codebase clean.
- 🔐 Never write sensitive data in comments — passwords and API keys should be in environment variables.
- ⚡ Write self-documenting code — good variable/function names reduce the need for comments.
❓ FAQ
Q1. Is there any official multi-line comment syntax in Python? > ❌ No! Python officially only has single-line comments (#). Writing multi-line comments using multiple # lines is the PEP 8 recommended approach. Triple-quoted strings are technically string objects, not comments.
Q2. What is the fundamental difference between a docstring and a comment? > A comment (#) is completely ignored by Python — it's neither executed nor stored in memory. A Docstring is an actual string object stored in the __doc__ attribute — accessible at runtime via help() and __doc__.
Q3. Do comments affect code performance/speed? > No! # comments have zero runtime impact because the Python interpreter skips them during the compilation phase. There's no trace of comments in bytecode. So don't worry about adding comments affecting performance.
Q4. Google Style, NumPy Style, reStructuredText — kaunsa docstring format use karna chahiye? > It depends on the team/project. Google Style is the most popular and readable — best for beginners. NumPy Style is common in data science projects. reStructuredText is used with Sphinx documentation. Pick one and be consistent.
Q5. Kya ek file mein sab jagah comments likhne chahiye? > No! Over-commenting is also a problem. Write comments only where the code's intent (purpose) isn't clear. Write self-documenting code — good variable names (total_price not tp) reduce the need for comments.
Q6. What is the role of comments like # type: ignore and # noqa? > These are special tool-specific comments. # type: ignore tells mypy (type checker) to skip this line. # noqa tells flake8/linter to suppress warnings on this line. They're not regular comments — they're directives for specific tools.
Q7. What is the benefit of writing examples in docstrings? > Huge benefit! Examples written with >>> in docstrings can be automatically tested by the doctest module: python -m doctest your_file.py. This becomes living documentation that also serves as tests.
Q8. Can you use Hindi or regional language in comments? > Technically yes — Python 3 supports UTF-8 so there won't be errors. But in professional projects, writing comments in English is standard because international teams need to understand the code.
Exam Focus
Revise definitions, diagrams, examples, and short-answer points for Python Comments.
Interview Use
Prepare one clear explanation, one practical example, and one common mistake for this Python Master Course topic.
Search Terms
python-master-course, python master course, python, master, course, basics, comments, python comments
Related Python Master Course Topics