Comments python
Comments in Python
Comments are lines in a Python program that are ignored by the interpreter during execution. They are used to explain the code, improve readability, and provide additional information for anyone reading the code.
Why Use Comments?
-
Improve code readability
-
Explain logic or provide metadata
-
Temporarily disable code
-
Include references or resources
Types of Comments in Python
Python supports three main types of comments:
-
Single-Line Comments
-
Multi-Line Comments
-
Docstring Comments
Single-Line Comments
A single-line comment begins with the # symbol. Anything after # on that line is ignored by the interpreter.
Example:
Output:
๐ Single-line comments are ideal for short explanations or notes in the code.
Multi-Line Comments
Python does not have a dedicated syntax for multi-line comments. However, you can achieve this in two common ways:
a) Using Multiple # Symbols
Each line starts with #.
Example:
Output:
Docstring Comments
Docstrings are string literals written using triple quotes (''' or """) placed right after a function, class, or module definition. They serve as documentation and can be accessed via the __doc__ attribute.
Example:
Output:
๐ Docstrings are commonly used to describe what a function, method, or class does.
Summary
-
Use
#for single-line comments. -
Use multiple
#symbols for multi-line comments. -
Use docstrings (
""") for documenting functions, classes, and modules.
๐Comments make your code easier to understand and maintain. They are especially valuable when collaborating with other developers or revisiting your own code after some time.