Python Comments
Learn how to write comments in Python, explain your code, document functions and classes, and make programs easier for humans to understand and maintain.
What You Will Learn
Comments
Understand what comments are and how Python handles them.
Syntax
Learn single-line, inline and multi-line commenting techniques.
Docstrings
Learn how documentation strings work inside Python functions, classes and modules.
Best Practices
Learn when comments help and when they create unnecessary clutter.
What Are Comments?
A comment is text written inside source code to explain something to a human reader.
Python completely ignores comments when executing a program. This means comments do not affect the result of your code.
Comments are mainly written for programmers. They can explain why a particular piece of code exists, describe a complicated calculation, or leave useful information for someone maintaining the program later.
Comments are for humans, not for the Python interpreter. Python skips them during execution.
Why Comments Matter
Good comments can make a program much easier to understand, especially when the code contains complex logic.
Comments can be useful for:
- Explaining complicated logic
- Describing why a particular decision was made
- Helping other developers understand your code
- Providing reminders during development
- Documenting assumptions and important details
Your code tells Python what to do. Your comments can tell another developer why it is being done.
Single-Line Comments
In Python, a comment begins with the hash symbol
#.
Everything written after # on that line
is treated as a comment.
# This is a comment
print("Hello, Python!")
Hello, Python!
The first line does not produce any output because Python ignores it.
Inline Comments
A comment can also appear on the same line as executable code. This is called an inline comment.
age = 25 # Store the user's age
print(age)
25
Inline comments can be useful when the meaning of a specific value or operation is not immediately obvious.
Too many comments placed beside every line can make your code harder to read.
Comments Above Code
A common practice is to place a comment immediately before a block of code that requires explanation.
# Calculate the total price after applying a 10% discount
price = 1000
discount = price * 0.10
final_price = price - discount
print(final_price)
900.0
Multi-Line Comments
Python does not have a dedicated multi-line comment syntax like some other programming languages.
For multiple comment lines, you can simply use
# at the beginning of each line.
# This program calculates
# the area of a rectangle
# using its length and width.
length = 10
width = 5
area = length * width
print(area)
50
Triple-quoted text is not technically a multi-line comment. It creates a string literal. When used in the right position, it can serve as a docstring.
Docstrings
A docstring is a string used to document a module, function, class or method.
Docstrings are normally written using triple quotes.
def greet():
"""Display a greeting message."""
print("Hello, Python!")
greet()
Hello, Python!
Unlike an ordinary comment, a docstring becomes part
of the Python object's documentation and can be accessed
using tools such as help() or the
__doc__ attribute.
Function & Class Docstrings
Docstrings become especially useful as your programs become larger.
Function Docstring
def calculate_square(number):
"""Return the square of a number."""
return number * number
print(calculate_square(5))
25
Class Docstring
class Student:
"""Represent a student in the learning system."""
pass
Clear documentation becomes increasingly important when working on larger applications or collaborating with other developers.
Good vs Bad Comments
Not every line of code needs a comment. A good comment adds information that is not obvious from the code itself.
Bad Comment
age = 25 # Set age to 25
The code is already obvious, so the comment provides very little value.
Better Comment
# Minimum age required to create an account
minimum_age = 18
This comment explains the purpose of the value rather than simply repeating what the code does.
Prefer comments that explain why something is done rather than comments that simply repeat what the code says.
Comments and Code Readability
Good code should ideally be understandable without requiring a comment on every line.
Meaningful variable names, clean structure and simple functions can often communicate intent better than large blocks of comments.
Less Helpful
# Store the user's age
user_age = 25
# Check whether the user is an adult
if user_age >= 18:
# Print that the user is an adult
print("Adult")
Cleaner
user_age = 25
if user_age >= 18:
print("Adult")
The second version is already easy to understand. Adding comments to every line would only create noise.
Commenting Out Code
During development, programmers sometimes temporarily disable a line of code by turning it into a comment.
print("Starting program")
# print("This line is temporarily disabled")
print("Program finished")
Starting program Program finished
The commented-out line is ignored by Python.
Temporary comments can be useful while experimenting, but unused code should generally be removed once it is no longer needed.
Common Mistakes
1. Forgetting the # Symbol
This is a comment
Python will try to interpret the text as code and may produce a syntax error.
2. Using Comments to Hide Poor Code
Comments should not be used as a replacement for clear variable names, readable functions or good program structure.
3. Confusing Docstrings with Comments
Triple-quoted strings are string literals. When placed as the first statement in a module, function, class or method, they serve as docstrings.
4. Writing Outdated Comments
If code changes, its comments may also need updating. An incorrect comment can be more confusing than having no comment at all.
Practice Exercises
Create Your First Comment
Write a Python program containing a comment and then print your name.
# Write your comment here
print("Your Name")
Add an Inline Comment
Create a variable containing your age and add an inline comment explaining what the variable stores.
Document a Function
Create a function named add_numbers()
and write a docstring explaining what the function
does.
Explain a Calculation
Write a program that calculates the area of a rectangle and add a useful comment explaining the calculation.
You've reached the end of this lesson.
Review the examples, open the Practice Lab, and mark this lesson complete when you're ready.