0
0
PythonHow-ToBeginner · 3 min read

How to Write Multiline Comments in Python Easily

In Python, you write multiline comments by enclosing the text within triple quotes like ''' comment ''' or """ comment """. These triple-quoted strings can span multiple lines and are commonly used for multiline comments or docstrings.
📐

Syntax

Use triple single quotes ''' or triple double quotes """ to write multiline comments. Everything between these quotes is treated as a string literal, which Python ignores if not assigned or used.

  • Triple single quotes: ''' comment '''
  • Triple double quotes: """ comment """
python
'''
This is a multiline comment
written using triple single quotes.
'''

"""
This is another multiline comment
using triple double quotes.
"""
💻

Example

This example shows how to use triple quotes to write a multiline comment that explains the code below.

python
'''
This function adds two numbers.
It takes two inputs and returns their sum.
'''
def add(a, b):
    return a + b

result = add(3, 5)
print(result)
Output
8
⚠️

Common Pitfalls

Some beginners confuse multiline comments with docstrings. Docstrings are also triple-quoted strings but are placed right after function or class definitions to document them. Using triple quotes outside of functions or classes works as multiline comments but they are actually string literals ignored by Python if unused.

Also, using multiple single-line comments (#) is a valid alternative but less neat for long comments.

python
# Wrong way: Using triple quotes inside code block as a comment but assigning it
comment = '''This is not a comment, it's a string assigned to a variable.'''

# Right way: Just use triple quotes without assignment
'''
This is a multiline comment.
'''
📊

Quick Reference

Summary tips for multiline comments in Python:

  • Use ''' comment ''' or """ comment """ for multiline comments.
  • Triple quotes create string literals ignored if not used.
  • Use # for single-line comments.
  • Docstrings use triple quotes but are placed immediately after function/class definitions.

Key Takeaways

Use triple quotes (''' or """) to write multiline comments in Python.
Triple-quoted strings act as comments if not assigned or used in code.
Docstrings also use triple quotes but serve to document functions or classes.
Single-line comments use the # symbol and are good for short notes.
Avoid assigning triple-quoted strings to variables if you want them as comments.