Python Comments
Learn how to add comments to your Python code for better documentation and readability.
Creating a Comment
Comments can be used to explain Python code, make the code more readable, or prevent execution when testing code.
Comments start with a #, and Python will ignore them:
Example
# This is a comment
print("Hello, World!") Comments can be placed at the end of a line, and Python will ignore the rest of the line:
Example
print("Hello, World!") # This is a comment A comment does not have to be text that explains the code, it can also be used to prevent Python from executing code:
Example
# print("Hello, World!")
print("Cheers, Mate!") Multiline Comments
Python does not really have a syntax for multiline comments. To add a multiline comment you could insert a # for each line:
Example
# This is a comment
# written in
# more than just one line
print("Hello, World!") Or, not quite as intended, you can use a multiline string. Since Python will ignore string literals that are not assigned to a variable, you can add a multiline string (triple quotes) in your code, and place your comment inside it:
Example
"""
This is a comment
written in
more than just one line
"""
print("Hello, World!") As long as the string is not assigned to a variable, Python will read the code, but then ignore it, and you have made a multiline comment.
Best Practices for Comments
- Use comments to explain why something is done, not just what is done
- Keep comments concise and relevant
- Update comments when you change the code
- Use proper grammar and spelling in comments
- Avoid obvious comments that don't add value
Good Comment Example
# Calculate compound interest using the formula A = P(1 + r/n)^(nt)
amount = principal * (1 + rate/frequency) ** (frequency * time) Poor Comment Example
# Add 1 to x
x = x + 1