Python Comments — Single-line, Multi-line & Docstrings

🐍 Python 3 🟢 Lesson 5 of 12 📂 Phase 1: Python Basics 📅 2026 Edition
How to write readable comments, single-line hash syntax, multi-line blocks, function docstrings (__doc__), and best practices for self-documenting code.
1Why Comments Matter

Comments are non-executable text lines ignored by the Python interpreter. They explain the why behind complex logic, document API contracts, and help other engineers (and your future self) understand code rationale.

21. Single-Line Comments (#)

Any text following a hash character # on that line is ignored by Python:

# This is a full-line comment
x = 100  # This is an inline comment explaining x
32. Multi-Line Comments & Triple-Quoted Strings

You can use consecutive single-line comments or triple quotes (""" or ''') for multi-line documentation:

"""
This is a multi-line comment block.
It can span across multiple lines
without needing a # on every line.
"""
43. Docstrings (Documentation Strings)

When a triple-quoted string is placed as the very first statement inside a function, class, or module, it becomes its official docstring, accessible via help(func) or func.__doc__.

💻 Complete Executable Code Example
def calculate_discount(price: float, discount_percent: float) -> float:
    """
    Calculate final discounted price.
    
    Args:
        price: Original item price in dollars
        discount_percent: Discount rate (e.g. 20 for 20%)
        
    Returns:
        Final discounted total
    """
    # Validate input discount range
    if not (0 <= discount_percent <= 100):
        raise ValueError("Discount must be between 0 and 100")
        
    discount_amount = price * (discount_percent / 100.0)
    return round(price - discount_amount, 2)

# Inspect the function's docstring dynamically
print("📖 Function Docstring:")
print(calculate_discount.__doc__)

# Execute function
print("💰 Final Price:", calculate_discount(150.0, 15.0))
⚠️ Common Pitfall: Over-commenting Obvious Code

Avoid comments that explain WHAT the syntax does (e.g., x = 1 # assign 1 to x). Instead, write comments that explain WHY a specific business logic or formula was chosen.

💻 Try It Yourself — Hands-on Practice Challenge

Add docstrings to a function and print help() metadata.

def greet_user(name: str, language: str = "en") -> str:
    """Returns a localized greeting for the specified user."""
    greetings = {"en": "Hello", "es": "Hola", "te": "Namaskaram", "fr": "Bonjour"}
    prefix = greetings.get(language, "Hello")
    return f"{prefix}, {name}!"

print(greet_user("Balaji", "te"))
print(greet_user("Alex", "es"))
print("Docstring content:", greet_user.__doc__)
Run This Code in Our Online Compiler →
Frequently Asked Questions (FAQ)

Q: What is the difference between a comment and a docstring?

Regular comments (#) are discarded by the compiler at parse time. Docstrings (""") are retained at runtime and stored in the __doc__ attribute of functions and classes for interactive help.

OC
Written by Our Compiler Technical Editorial Team
Reviewed for accuracy & tested on Python 3.12+ runtime · Last updated August 2026