Comments are used to explain Python code and make it more readable.
Comments can also be used to prevent code from being executed during testing.
Python ignores comments when running a program.
Creating a Comment
Comments start with the # character.
Example:
# This is a comment
print("Hello, World!")
Output:
Hello, World!
Comments at the End of a Line
Comments can also be placed after a statement.
Example:
print("Hello, World!") # This is a comment
Output:
Hello, World!
Multi-Line Comments
Python does not have a dedicated syntax for multi-line comments.
You can use multiple # symbols:
# This is a comment
# written in
# more than one line
print("Hello, World!")
Multi-Line Strings as Comments
You can also use triple quotes to create multi-line text blocks that are often used as comments.
Example:
"""
This is a multi-line comment.
It can span multiple lines.
"""
print("Hello, World!")
Output:
Hello, World!
Why Use Comments?
Comments help you:
- Explain your code
- Make programs easier to understand
- Leave notes for yourself and other developers
- Temporarily disable code during testing
Example:
name = "John" # Store user name
# Display welcome message
print("Welcome", name)
Output:
Welcome John
Best Practice
Write comments that explain why something is done, not just what the code does.
Good:
# Calculate discount for premium users
discount = price * 0.20
Not so useful:
# Multiply price by 0.20
discount = price * 0.20
Summary
- Comments start with the
#symbol. - Python ignores comments when executing code.
- Comments can be on their own line or at the end of a line.
- Multiple
#lines can be used for multi-line comments. - Triple quotes can be used for longer comment blocks.
- Comments improve code readability and maintenance.