Guide Python Beginner

4.5 Comments

Single-line comments, why Python has no dedicated multi-line comment syntax, docstrings and the __doc__ attribute, and best practices for commenting code.

5 min read

1.1 What Is a Comment?

A comment is a note written for people reading the code. Python ignores comments when it runs the program.

Comments are useful when they explain a decision, a warning, or a part of the code that is not obvious.

flowchart LR A[Python file] --> B{Line starts with #?} B -->|Yes| C[Python ignores the comment] B -->|No| D[Python reads and executes the code]

1.2 Single-Line Comments

Start a comment with #. Everything after # on that line is ignored:

# Check the API three times because the service may respond slowly.
max_retries = 3

You can also place a short comment after code:

timeout_seconds = 30  # Keep the request from waiting forever.

Use an end-of-line comment only when it remains easy to read.

1.3 Comments Before Code

A comment can explain the purpose of the next few lines:

# Skip temporary files before uploading the directory to S3.
for file_name in files:
    if not file_name.endswith(".tmp"):
        upload(file_name)

The comment explains why the condition exists. The code already shows what the condition does.

1.4 Multi-Line Comments

Python does not have a special multi-line comment symbol. For a longer comment, use # on each line:

# This script checks the health of each service.
# It prints a warning when a service is not running.
# The output can be used by a monitoring job.

This is the clearest and most reliable way to write a multi-line comment.

1.5 Comments and Triple Quotes Are Different

Triple quotes create a string, not a real multi-line comment:

"""
This looks like a comment,
but Python treats it as a string.
"""

An unused string may appear to work like a comment, but it is not the correct general-purpose comment style. Use # for comments.

1.6 What Is a Docstring?

A docstring is text that documents a module, function, class, or method. It is written inside triple quotes as the first statement in that object.

def check_server(server_name):
    """Return the health status of a server."""
    return f"{server_name} is healthy"

Unlike a normal comment, a docstring is available while the program runs:

print(check_server.__doc__)

Output:

Return the health status of a server.

Python’s help() function and many editors can display docstrings:

help(check_server)

1.7 Function Docstrings

Use a function docstring to explain what the function does, its inputs, and its result when that information is useful:

def calculate_retry_delay(attempt, base_delay=2):
    """Return the delay before the next retry attempt."""
    return base_delay ** attempt

The function name and code show how it works. The docstring gives a short explanation for someone who wants to use it.

1.8 Module and Class Docstrings

A module docstring goes at the top of a Python file:

"""Tools for checking application health."""

import requests

A class docstring goes immediately inside the class:

class HealthChecker:
    """Check whether an application endpoint is responding."""

    pass

1.9 Good and Bad Comments

This comment does not add much information:

# Add one to count.
count = count + 1

The code is already clear. This comment is more useful:

# Count only successful responses so failed checks are reported separately.
successful_checks += 1

Good comments usually explain why, not only what.

1.10 Keep Comments Correct

Update a comment when the code changes. A comment that disagrees with the code can mislead someone:

# Retry five times.
for attempt in range(3):
    retry_request()

The comment and code disagree. Change one of them so they describe the same behavior.

1.11 Comments in DevOps Scripts

Comments are especially useful in automation scripts for explaining:

  • Why a retry or timeout value was chosen
  • Why a resource is skipped
  • What permission a cloud API call requires
  • Why a command is safe or potentially destructive
  • What format an input file must use
# The cleanup is limited to objects older than 30 days.
# Do not remove newer objects because they may be needed for recovery.
if object_age_days > 30:
    delete_object(object_name)

Never put passwords, access keys, tokens, or other secrets in comments. Comments are stored in the source code and may be shared with the repository.

1.12 Practice Exercise

Add useful comments and a docstring to this script:

def check_services(services):
    """Print the status of each service in the list."""
    for service in services:
        # Treat only running services as healthy.
        if service["status"] == "running":
            print(f"{service['name']} is healthy")
        else:
            print(f"{service['name']} needs attention")


services = [
    {"name": "api", "status": "running"},
    {"name": "worker", "status": "stopped"},
]

check_services(services)

Add one comment explaining a decision, then add a docstring to the function.

Interview Questions

  • What is a comment in Python?
  • How do you write a single-line comment?
  • How do you write a multi-line comment?
  • Are triple-quoted strings the same as comments?
  • What is a docstring?
  • Where should a function docstring be placed?
  • What is the difference between a comment and a docstring?
  • What makes a comment useful?

Quick Interview Answer

A Python comment starts with #, and Python ignores it when running the program. Python does not have a special multi-line comment syntax, so we use # on each line. A docstring is different: it is a triple-quoted string placed first inside a module, function, or class, and it can be viewed through __doc__ or help().

Key Takeaways

  • Use # to write comments.
  • Use comments to explain why code exists.
  • Use one # on each line for multi-line comments.
  • Use docstrings to document reusable functions, classes, and modules.
  • Keep comments short, clear, and up to date.
  • Never store secrets in source code comments.

Add More Questions to This Guide

Know a question that should be here? Share it and help the community!

Open Google Form