Writing clean and understandable code is essential for any programmer. Python provides two main tools for adding explanations within your code: comments and docstrings.
This article will walk you through both, using five simple examples to make your understanding clear.
Example 1: Single-line Comments
# This is a single-line comment
print("Hello, World!") # This prints a greeting
Single-line comments start with the hash symbol (#
). They are ignored by the Python interpreter and help you or others understand what the code is doing.
Example 2: Multi-line Comments
# This is a multi-line comment
# explaining what the following code does
name = "Alice"
print("Hello,", name)
Python doesn’t have a true multi-line comment syntax, but you can use multiple single-line comments in a row to achieve the same effect.
Example 3: Basic Docstring in a Function
def greet(name):
"""
This function greets the person passed as argument.
"""
print("Hello,", name)
Docstrings are enclosed in triple quotes and are used to describe what a function, class, or module does. They are accessible using help()
in Python.
Example 4: Docstring in a Class
class Person:
"""
Represents a person with a name.
"""
def __init__(self, name):
"""
Initializes the person's name.
"""
self.name = name
def greet(self):
"""
Prints a greeting using the person's name.
"""
print("Hello,", self.name)
Each class and method can have its own docstring to explain its purpose and usage.
Example 5: Accessing Docstrings Using help()
def square(n):
"""
Returns the square of a number.
"""
return n * n
# Access the docstring
help(square)
Python’s built-in help()
function can display the docstring of any function, class, or module. This is very useful for documentation and readability.
Summary
- Use single-line comments to explain specific lines or short sections of code.
- Use docstrings to describe the purpose of functions, classes, and modules.
- Stick to clean, concise, and helpful explanations to improve code readability.
Adding comments and docstrings is one of the simplest and most effective habits to make your Python code more maintainable and easier to understand.