1. Creating Comments:
- Comments are used to add notes or explanations to your code.
- In Python, you can create single-line comments using the
#
symbol. - Example:python
# This is a single-line comment print("Hello, Python!") # This is another comment
2. Multi-line Comments:
- Python doesn't have a specific syntax for multi-line comments like some other programming languages.
- However, you can use triple quotes (
'''
or"""
) to create multi-line comments in Python. - While technically not a comment, it serves the same purpose by acting as a multi-line string that is ignored by the interpreter.
- Example:python
''' This is a multi-line comment. It can span multiple lines. ''' print("Hello, Python!")
3. Commenting Out Code:
- Comments are also useful for temporarily disabling or "commenting out" a piece of code for testing or debugging purposes.
- By adding a
#
symbol at the beginning of a line of code, that line will be ignored by the interpreter. - Example:python
# print("Hello, Python!") print("This line is not commented.")
4. Docstrings:
- Docstrings are used to provide documentation for functions, modules, and classes.
- They are enclosed in triple quotes (
'''
or"""
) and can span multiple lines. - Docstrings are typically placed as the first statement within a function, module, or class definition.
- Example:python
def greet(name): """ This function greets the given name. """ print("Hello, " + name)
Using comments effectively in your code can improve its readability, understandability, and maintainability. It's good practice to add comments to explain complex logic, document assumptions, or provide context for future readers.
<< Previous Next >>