Python Tutoring Online
 Home            

Python Comments – How to Write Comments in Python

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.

What Is a Comment in Python?

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.

Python
# This is a Python comment

print("Hello Python")

Output


Hello Python

The comment is not executed, so only the print() statement produces output.

Python Comment Syntax

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:

Python
# Store a number in a variable
number = 10

print(number)

Output


10

The first line is a comment. The assignment statement and print() statement are executed normally.

Single-Line Comments in Python

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.

Python
# Store the student name
name = "Alice"

# Display the student name
print(name)

Output


Alice

The lines beginning with # are comments. They explain the purpose of the code but do not affect the program output.

Why Are Comments Important in Python?

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:

Comments Before Python Code

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.

Python
# Calculate the average score

math = 80
science = 90

average = (math + science) / 2

print(average)

Output


85.0

The comment explains the purpose of the calculation without affecting the result.

Inline Comments in Python

Python also allows a comment to appear after executable code on the same line. This is called an inline comment.

Python
age = 20  # Store the age

print(age)

Output


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 Comments on Multiple Lines

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.

Python
# This program calculates the average
# of two student scores.
# The result is then displayed.

math = 80
science = 90

average = (math + science) / 2

print(average)

Output


85.0

Each line beginning with # is a separate Python comment. Together, these comments can be used to explain a larger section of code.

How to Comment Multiple Lines in Python

If you need to comment several lines of Python code, place # at the beginning of each line.

Python
# number = 10
# number = number + 5
# print(number)

print("The code above is commented out")

Output


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.

Can Triple Quotes Be Used as Python Comments?

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:

Python
"""
This is a string literal.
It is not technically a comment.
"""

print("Python")

Output


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.

Python Comments vs Triple-Quoted Strings

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

What Is a Python Docstring?

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.

Example: Python Function Docstring

Python
def greet(name):
    """Return a greeting message."""
    return "Hello " + name

print(greet("Alice"))

Output


Hello Alice

The triple-quoted text is the function's docstring. It describes what the function does.

Accessing a Python Docstring

Python
def square(number):
    """Return the square of a number."""
    return number ** 2

print(square.__doc__)

Output


Return the square of a number.

The __doc__ attribute provides access to the documentation string associated with the function.

Module Docstrings in Python

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.

Class Docstrings in Python

Classes can also have docstrings. The docstring should normally be the first statement inside the class definition.

Python
class Student:
    """Represent a student."""

    def __init__(self, name):
        self.name = name

student = Student("Alice")

print(student.__class__.__doc__)

Output


Represent a student.

Using Comments to Explain Python Code

One of the most useful purposes of a Python comment is to explain code that may not be immediately obvious to another programmer.

Python
# Calculate the average score

math = 80
science = 90

average = (math + science) / 2

print("Average:", average)

Output


Average: 85.0

The comment tells the reader why the calculation is being performed.

Explain Why Instead of What

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.

Using Python Comments for Debugging

Comments can be useful during debugging when you temporarily want to prevent a statement from executing.

Python
number = 10

# print("Debug value:", number)

print(number * 2)

Output


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 in Python if Statements

Comments can be used to explain the purpose of conditions in an if statement.

Python
age = 20

if age >= 18:
    # Check the adult condition.
    print("Adult")

Output


Adult

The comment is indented because it is located inside the if block.

Comments in Python Loops

Comments can also explain the purpose of a loop or an operation performed during each iteration.

Python
numbers = [10, 20, 30]

# Display every number in the list.
for number in numbers:
    print(number)

Output


10
20
30

Comments Inside Python Functions

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.

Python
def calculate_total(price, tax):
    # Add the tax amount to the original price.
    return price + tax

print(calculate_total(100, 15))

Output


115

Python Comments and Indentation

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.

Python
age = 20

if age >= 18:
    # This statement runs for adults.
    print("Adult")

Output


Adult

Understanding indentation is important when writing comments inside conditional statements, loops, functions and other Python blocks.

Python Comments Inside Strings

A # character inside a Python string is not treated as the beginning of a comment. It is simply part of the string.

Python
message = "# This is text, not a comment"

print(message)

Output


# This is text, not a comment

Python only treats # as a comment marker when it occurs outside a string literal.

Comments in Larger Python Programs

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.

Python Comment Best Practices

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.

Good and Bad Python Comments

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.

Common Python Comment Mistakes

Beginners sometimes use comments incorrectly or add comments that make their programs harder to maintain.

Python Comments vs Docstrings

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

Frequently Asked Questions About Python Comments

How do you write a comment in Python?

Use the # symbol before the text you want to comment. Python ignores everything after the # on that line.

Python
# This is a Python comment

print("Hello")

How do you comment multiple lines in Python?

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.

Does Python have multiline comments?

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.

What does the # symbol mean in Python?

The # symbol starts a comment when it appears outside a string. Python ignores the text from the # to the end of the line.

Are triple quotes comments in Python?

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.

What is a docstring in Python?

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.

Can Python comments affect program execution?

Ordinary comments beginning with # do not affect Python program execution. They are ignored by the Python interpreter.

Why are comments important in Python?

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.

Summary of Python Comments

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.

Related Python Tutorials

Continue learning Python with these related tutorials:

Need Help Learning Python?

Having difficulty understanding Python comments, docstrings, syntax or other Python fundamentals? An experienced Python tutor can help you learn programming concepts through clear explanations and practical coding examples.

One-to-one Python tutoring provides guided coding practice and personalized help with Python fundamentals, assignments, projects and programming problems.

Get Python Tutoring Help




Stuck Learning Python?

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.

    Get Python Tutoring

PythonTutor.net

Home    Tutorial     Online Live Trainings    Contact Us           © 2026 All rights reserved by www.PythonTutor.net