|
| Home |
|---|
Python comments are notes written inside Python source code to explain, describe or document a program. Comments are written for people reading the code and are not executed as normal Python statements.
Comments are useful when learning Python, writing assignments, debugging programs and developing larger applications. They can explain what a section of code does, describe an important programming decision and make Python programs easier to read and maintain.
The most common way to write a comment in Python is to use the
hash symbol (#). Python ignores everything
from the # character to the end of that line.
In this tutorial, you will learn how to write Python comments, use single-line and inline comments, write comments across multiple lines, understand Python docstrings, use comments while debugging and follow best practices for writing clear and useful comments.
A comment in Python is text added to a Python program to provide information for programmers. Comments can explain how a program works, describe a complicated section of code or provide useful information about a particular programming decision.
Python comments are ignored by the Python interpreter. This means that ordinary comments do not change the way the program executes.
# This is a Python comment
print("Hello Python")
Hello Python
The comment is not executed, so only the print() statement
produces output.
The basic syntax for a Python comment is very simple. Place the
# symbol before the text that you want Python to treat as
a comment.
# This is a comment
Python ignores the comment from the # symbol until the end
of that physical line.
For example:
# Store a number in a variable
number = 10
print(number)
10
The first line is a comment. The assignment statement and
print() statement are executed normally.
A single-line comment begins with the
# symbol and continues until the end of the line.
Single-line comments are the most common type of comment used in
Python programs.
# Store the student name
name = "Alice"
# Display the student name
print(name)
Alice
The lines beginning with # are comments. They explain the
purpose of the code but do not affect the program output.
Comments are particularly useful when Python programs become longer or more complicated. A programmer may understand code when writing it but have difficulty remembering why a particular approach was used several months later.
Useful Python comments can help programmers:
A comment can be placed on the line before the code it explains. This is often a good way to document a section of a Python program.
# Calculate the average score
math = 80
science = 90
average = (math + science) / 2
print(average)
85.0
The comment explains the purpose of the calculation without affecting the result.
Python also allows a comment to appear after executable code on the same line. This is called an inline comment.
age = 20 # Store the age
print(age)
20
Python executes the statement before the # and ignores the
comment after it.
Inline comments are useful for short explanations. However, they should not be overused because placing comments on every line can make a program harder to read.
Python does not have a dedicated multiline-comment syntax. When a
longer explanation is required, the normal approach is to place a
# symbol at the beginning of each line.
# This program calculates the average
# of two student scores.
# The result is then displayed.
math = 80
science = 90
average = (math + science) / 2
print(average)
85.0
Each line beginning with # is a separate Python comment.
Together, these comments can be used to explain a larger section of
code.
If you need to comment several lines of Python code, place
# at the beginning of each line.
# number = 10
# number = number + 5
# print(number)
print("The code above is commented out")
The code above is commented out
The three lines beginning with # are ignored by Python.
Most Python code editors also provide a shortcut for commenting and
uncommenting selected lines.
You may see triple quotes such as """ or
''' being used to create what looks like a multiline
comment.
However, it is important to understand the technical difference: triple quotes create a string literal, not a special Python multiline-comment syntax.
For example:
"""
This is a string literal.
It is not technically a comment.
"""
print("Python")
Python
Although this type of unused string may appear similar to a multiline
comment, it is actually a string literal. For ordinary multiline
comments, using # on each line is clearer and more
appropriate.
Understanding the difference between comments and triple-quoted strings is important when learning Python.
| Feature | Python Comment | Triple-Quoted String |
|---|---|---|
| Syntax | # |
""" """ or ''' ''' |
| Type | Comment | String literal |
| Normal purpose | Explain source code | Represent text or provide documentation |
| Can be used as a docstring? | No | Yes |
A Python docstring is a string used to document a module, class, function or method. Docstrings are normally written using triple quotes and placed as the first statement inside the object being documented.
Unlike an ordinary comment, a docstring can be accessed by Python at
runtime using the __doc__ attribute.
def greet(name):
"""Return a greeting message."""
return "Hello " + name
print(greet("Alice"))
Hello Alice
The triple-quoted text is the function's docstring. It describes what the function does.
def square(number):
"""Return the square of a number."""
return number ** 2
print(square.__doc__)
Return the square of a number.
The __doc__ attribute provides access to the documentation
string associated with the function.
A Python file can also contain a module-level docstring. It is normally placed at the beginning of the file and describes the purpose of the module.
"""
Utilities for processing student records.
"""
def calculate_average(scores):
return sum(scores) / len(scores)
Module docstrings are particularly useful when developing larger Python projects containing multiple modules.
Classes can also have docstrings. The docstring should normally be the first statement inside the class definition.
class Student:
"""Represent a student."""
def __init__(self, name):
self.name = name
student = Student("Alice")
print(student.__class__.__doc__)
Represent a student.
One of the most useful purposes of a Python comment is to explain code that may not be immediately obvious to another programmer.
# Calculate the average score
math = 80
science = 90
average = (math + science) / 2
print("Average:", average)
Average: 85.0
The comment tells the reader why the calculation is being performed.
Good comments often explain why a particular piece of code exists instead of simply describing what the code obviously does.
For example, this comment provides useful information:
# Wait for the API rate limit to reset.
delay = 60
A comment such as # Set delay to 60 provides much less
information because the code already makes that operation obvious.
Comments can be useful during debugging when you temporarily want to prevent a statement from executing.
number = 10
# print("Debug value:", number)
print(number * 2)
20
The commented-out print() statement is ignored by Python.
This can be useful for testing different parts of a program.
For larger debugging tasks, however, a debugger or logging system is usually more appropriate than commenting out large sections of code.
Comments can be used to explain the purpose of conditions in an
if statement.
age = 20
if age >= 18:
# Check the adult condition.
print("Adult")
Adult
The comment is indented because it is located inside the
if block.
Comments can also explain the purpose of a loop or an operation performed during each iteration.
numbers = [10, 20, 30]
# Display every number in the list.
for number in numbers:
print(number)
10
20
30
Comments can explain an implementation detail inside a function. When the purpose of the entire function needs to be documented, a docstring is usually a better choice.
def calculate_total(price, tax):
# Add the tax amount to the original price.
return price + tax
print(calculate_total(100, 15))
115
Comments can appear inside an indented Python block. When a comment belongs to a particular block, it should normally use the same indentation level as the code it explains.
age = 20
if age >= 18:
# This statement runs for adults.
print("Adult")
Adult
Understanding indentation is important when writing comments inside conditional statements, loops, functions and other Python blocks.
A # character inside a Python string is not treated as the
beginning of a comment. It is simply part of the string.
message = "# This is text, not a comment"
print(message)
# This is text, not a comment
Python only treats # as a comment marker when it occurs
outside a string literal.
Comments become particularly useful when working on larger Python applications or projects with multiple programmers.
Useful comments can explain business rules, unusual algorithms, important assumptions, external requirements or decisions that are not obvious from the code itself.
However, comments should not replace clear programming practices. Meaningful variable names, well-designed functions and readable code should be used together with comments.
Good Python comments should be clear, concise and useful. The purpose of a comment is to help the reader understand something that may not be obvious from the code.
Consider this example:
# Add 1 to x
x += 1
The comment does not provide much additional information because the operation is already obvious.
A more useful comment might explain the reason for the operation:
# Move to the next page of search results.
page += 1
The second comment provides information that cannot be determined simply by looking at the code.
Beginners sometimes use comments incorrectly or add comments that make their programs harder to maintain.
| Feature | Python Comments | Python Docstrings |
|---|---|---|
| Syntax | # |
""" """ or ''' ''' |
| Purpose | Explain source code | Document modules, classes and functions |
Available through __doc__ |
No | Yes |
| Common use | Implementation explanations | Program and API documentation |
Use the # symbol before the text you want to comment.
Python ignores everything after the # on that line.
# This is a Python comment
print("Hello")
Python does not have a dedicated multiline-comment delimiter. The
recommended approach is to place the # symbol at the
beginning of each line that you want to comment.
Python does not have a dedicated multiline comment syntax. Multiple
lines can be commented by placing # at the beginning of
each line. Triple-quoted strings are not technically multiline
comments.
The # symbol starts a comment when it appears outside a
string. Python ignores the text from the # to the end of
the line.
No. Triple quotes create string literals. When a triple-quoted string is placed as the first statement inside a module, class, function or method, it can serve as a docstring. It is therefore more accurate to distinguish triple-quoted strings from ordinary Python comments.
A docstring is a string used to document a Python module, class,
function or method. It is normally placed as the first statement inside
the object being documented and can be accessed through its
__doc__ attribute.
Ordinary comments beginning with # do not affect Python
program execution. They are ignored by the Python interpreter.
Comments make Python programs easier to understand, maintain and debug. They are especially useful for explaining complex logic, important decisions and code that may not be immediately obvious to another programmer.
Python comments are used to explain and document
Python source code. The standard way to write a Python comment is to
use the # symbol.
Python supports single-line comments and inline comments. When a longer
comment is required, programmers normally place # at the
beginning of each line.
Python does not have a dedicated multiline-comment syntax. Triple-quoted text creates a string literal and is commonly used for docstrings when placed at the beginning of a module, class, function or method.
Good comments should be concise, accurate and useful. They should add information that helps a reader understand the code rather than simply repeat what the code already says.
Continue learning Python with these related tutorials:
Struggling with Python syntax, assignments or debugging errors? Learning alone can be frustrating.
Get 1-on-1 Python tutoring and learn faster with clear explanations, real examples and live help.
Home Tutorial Online Live Trainings Contact Us © 2026 All rights reserved by www.PythonTutor.net