Comments vs DocStrings
Comments and docstrings are both ways to add explanatory text to your code, but they serve different purposes and have different formatting conventions. Here's a breakdown of their comparison and contrast:
Purpose
Explain specific code sections
Document classes, functions, or modules
Placement
Within the code block being explained
At the beginning of the definition
Formatting
Language-dependent (usually single or multi-line)
Language-specific formatting conventions (e.g., triple quotes in Python)
Permanence
Can be temporary (for notes/reminders)
Meant to be permanent documentation
Level of Detail
Brief explanations
Comprehensive descriptions
When Should I use a Comment or DocString?
Use comments to explain "why" you wrote a specific piece of code.
Use docstrings to document "what" a class, function, or module does and "how" to use it.
The docstring provides an explanation of the function and what it does:
Function Purpose: To create a historical character with a name and era.
Arguments: It defines a section titled "Args" that explains each argument taken by the function:
name: The name of the historical figure.
era: The historical era the figure belongs to.
Returns: Outlines the that a description of the character is returned from the function.
This docstring improves code readability and maintainability by providing clear explanations for anyone using the create_historic_character
function.
Last updated
Comments
Structure: Comments can be single-line (// in C++, # in Python) or multi-line (/* ... */ in C++) depending on the programming language. They are typically placed within the code block they are explaining.
Use: Comments are used to explain specific lines of code, algorithms, or logic choices made by the programmer. They can also be used for temporary notes or reminders to be removed later such as #TODO