How to Write Multiline Comments in Python Easily
''' 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 """
''' 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.
''' 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)
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.
# 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.