Python - Comments

Overview

Estimated time: 10–15 minutes

Learn how to write comments in Python: single-line comments with #, multi-line comment patterns, and how docstrings differ from comments.

Learning Objectives

  • Use # for single-line comments.
  • Understand multi-line comment patterns using line prefixes and string literals.
  • Know what docstrings are for and how tools read them.

Prerequisites

Single-line comments

# This is a comment explaining the next line
x = 42  # Inline comment can follow code
print(x)

Expected Output: 42

Multi-line comments (two patterns)

# Pattern 1: multiple single-line comments
# Explain step 1
# Explain step 2

# Pattern 2: block string literal not assigned (used as a block note)
"""
This block string is sometimes used as a multi-line comment.
Be cautious: it creates a string object at runtime.
Prefer multiple # lines for true comments.
"""

Docstrings vs comments

def area(r: float) -> float:
    """Return area of a circle.

    Parameters
    ----------
    r: radius in meters
    """
    from math import pi
    return pi * r * r

Docstrings document modules, classes, and functions. Tools like help() and IDEs surface them. Use comments for implementation notes.

Common Pitfalls

  • Using triple-quoted strings as comments everywhere: they are string objects at runtime; stick to # for comments.
  • Out-of-date comments: keep comments close to code and update them during refactors.

Checks for Understanding

  1. What symbol starts a Python comment?
  2. When would you choose a docstring over a comment?
Show answers
  1. #
  2. When documenting a public API: modules, classes, or functions for users.

Exercises

  1. Add comments to a short script explaining each step.
  2. Write a function with a docstring and view it with help() in the REPL.