Python Comments
Comments are used in Python to add explanations or notes to the code. They are not executed and do not affect the program’s functionality. Comments are crucial for enhancing code readability and for providing context to readers.
A good comment explains why the code does something, not what it does — the code itself already shows the what.
# Bad: restates the obvious
x = x + 1 # add 1 to x
# Good: explains the reason
x = x + 1 # advance to the next page; pages are 1-indexedDiagram:
graph LR
A[Source line] --> B{Contains #?}
B -->|Yes| C[Run code before #]
C --> D[Ignore text after #]
B -->|No| E[Run the whole line]
Single-line Comments
Section titled “Single-line Comments”In Python, single-line comments start with the # symbol. Anything following the # on that line is considered a comment.
Example:
Section titled “Example:”# This is a single-line comment
print("Hello, World!") # This is also a comment after codeMulti-line Comments
Section titled “Multi-line Comments”While Python does not have a specific syntax for multi-line comments, you can use triple-quotes (''' or """) to create multi-line string literals. Even though these are technically strings, they are often used as a workaround for creating multi-line comments.
Example:
Section titled “Example:”'''
This is a multi-line comment.
It spans multiple lines.
'''
"""
Another way to create a multi-line comment.
Use triple-quotes to start and end the comment block.
"""
print("Hello, World!")Comments for Code Documentation
Section titled “Comments for Code Documentation”In addition to adding comments for clarifying code, Python has a convention for using docstrings to document functions, modules, and classes. Docstrings are enclosed in triple-quotes and are used to provide information about the code element.
Example:
Section titled “Example:”def add_numbers(a, b):
"""
This function adds two numbers and returns the result.
Parameters:
- a (int): The first number.
- b (int): The second number.
Returns:
int: The sum of a and b.
"""
return a + b
# Usage of the function
result = add_numbers(5, 3)
print("Result:", result)Accessing a Docstring
Section titled “Accessing a Docstring”Unlike ordinary comments, docstrings are kept by Python at runtime. You can read them with the built-in help() function or the __doc__ attribute — this is how editors and help() show documentation.
print(add_numbers.__doc__) # prints the docstring text
help(add_numbers) # prints formatted helpCommenting Out Code
Section titled “Commenting Out Code”During debugging it is common to temporarily disable a line by turning it into a comment. Most editors do this for a whole selection with Ctrl + /.
print("This runs")
# print("This line is disabled for now")
print("This runs too")TODO and FIXME Conventions
Section titled “TODO and FIXME Conventions”Teams use tagged comments so tools and editors can find pending work. Common tags include TODO, FIXME, and NOTE:
# TODO: handle negative numbers
# FIXME: this crashes when the list is empty
# NOTE: prices are stored in cents, not dollarsThe Shebang Line
Section titled “The Shebang Line”On Linux and macOS, the first line of an executable script can be a special comment called a shebang. It tells the system which interpreter to use, so the script can be run directly:
#!/usr/bin/env python3
print("Run me directly with ./script.py")Best Practices for Comments
Section titled “Best Practices for Comments”-
Be Clear and Concise: Write comments that are easy to understand. Avoid unnecessary comments that restate the obvious.
-
Keep Comments Updated: If code changes, remember to update the associated comments to ensure accuracy.
-
Use Docstrings for Documentation: For functions, modules, and classes, utilize docstrings to provide comprehensive documentation.
-
Avoid Excessive Comments: Code should be self-explanatory whenever possible. Avoid cluttering your code with excessive comments.
Comments play a crucial role in effective communication within your codebase. Use them wisely to make your Python code more understandable and maintainable.
Explore more Python coding practices with our tutorials on Python Central Hub!
Try it: Comments Exercises
Section titled “Try it: Comments Exercises”Exercise 1 – Single-Line Comment
Section titled “Exercise 1 – Single-Line Comment”Exercise 2 – Inline Comment
Section titled “Exercise 2 – Inline Comment”Exercise 3 – Multi-Line Comment (Docstring)
Section titled “Exercise 3 – Multi-Line Comment (Docstring)”pch.coffeeTagline
pch.coffeeCtapch.feedbackHeading
pch.feedbackSubheading