Comments are programmer-written annotations included in source code to explain logic, clarify complex algorithms, and prevent lines of code from executing during debugging. The Python interpreter completely ignores comments during compilation. In this lesson, you will learn how to write clean, professional single-line comments, multi-line blocks, and standardized Docstrings (PEP 257).
# Symbol)Any text following the hash symbol (#) on a line is treated as a comment:
# This is a full-line comment explaining the variable below
conversion_rate = 83.25 # USD to INR conversion rate (inline comment)
# Best Practice (PEP 8): Separate inline comments with at least 2 spaces!
Unlike C++ or Java which use /* ... */, Python provides two standard ways to comment multiple lines:
# Step 1: Query student records from the database
# Step 2: Calculate total semester grade point average (GPA)
# Step 3: Send automated email notification to student portal
"""
This multi-line string is not assigned to any variable.
The CPython compiler parses it as a literal, evaluates it,
finds no references to it, and immediately discards it!
"""
print("Application running...")
A docstring is fundamentally different from a regular comment. When a triple-quoted string appears as the first statement inside a function, class, or module, Python preserves it as the docstring metadata attribute (__doc__):
def calculate_simple_interest(principal: float, rate: float, time: float) -> float:
"""
Calculate and return the simple interest on a loan.
Parameters:
principal (float): The principal investment amount.
rate (float): Annual interest percentage rate (e.g. 7.5).
time (float): Time duration in years.
Returns:
float: Total interest earned over the given period.
"""
return (principal * rate * time) / 100
# Accessing the docstring at runtime:
print(calculate_simple_interest.__doc__)
# Python's built-in interactive help system reads docstrings directly:
# help(calculate_simple_interest)
• Keep Comments Up to Date: An out-of-date comment that contradicts the code is worse than no comment at all!
• Explain "Why", Not "What": Do not state the obvious. Good comments explain why an algorithm or business rule was chosen, not what the syntax already reveals.
• Complete Sentences: Always start comments with a capital letter and end with a period if it is a complete sentence.
__doc__ attributes to automatically generate professional HTML documentation websites for Python libraries.