Skip to main content

Command Palette

Search for a command to run...

Python Comment Vs DocStrings

Updated
2 min read
Python Comment Vs DocStrings
A

👋 Welcome to my Hashnode blog! I'm a tech enthusiast and cloud advocate with expertise in IT, backup solutions, and cloud technologies. Currently, I’m diving deep into Python and exploring its applications in automation and data management. I share insights, tutorials, and tips on all things tech, aiming to help fellow developers and enthusiasts. Join me on this journey of learning and innovation!

In Python, comments and docstrings are both used to document code, but they serve different purposes and have different syntax.

1. Comments:

  • Syntax: Start with a # symbol.

  • Purpose: To explain or annotate specific parts of the code.

  • Scope: Not accessible by Python tools or the program itself; used only for developers reading the code.

Example:

pythonCopy code# This is a comment explaining the following line of code
x = 10  # Initialize variable x with value 10

2. Docstrings:

  • Syntax: Enclosed in triple quotes (""" """ or ''' ''').

  • Purpose: To document functions, classes, or modules. They describe what the function/class/module does.

  • Scope: Accessible via tools like help() or by the attribute __doc__ for introspection.

Example:

pythonCopy codedef add(a, b):
    """
    This function adds two numbers.

    Parameters:
    a (int): The first number.
    b (int): The second number.

    Returns:
    int: The sum of a and b.
    """
    return a + b

Key Differences:

  1. Usage: Comments are for inline explanations, while docstrings document larger code structures like functions, classes, or modules.

  2. Syntax: Comments use #, while docstrings use triple quotes.

  3. Access: Docstrings are stored in the __doc__ attribute and can be accessed programmatically, while comments are ignored during execution.

  4. Purpose: Comments clarify parts of the code for developers, while docstrings describe the functionality of functions/classes/modules for both developers and tools.

More from this blog

PythonChallenge

11 posts

Welcome to my Python blog, where I share my journey of learning and exploring the versatile world of Python programming! 🌟

Let’s code, learn, and grow together in the world of Python programming!