How to comment in Python

Comments in Python help developers document code and make it more maintainable. Whether you're writing simple inline notes or detailed function documentation, Python's commenting system provides flexible options for adding clarity to your programs.

This guide covers essential commenting techniques, best practices, and real-world examples—all created with Claude, an AI assistant built by Anthropic. You'll learn to write clearer, more maintainable code.

Using the # symbol for single-line comments

# This is a simple comment in Python
print("Hello World")  # This code will be executed
Hello World

The # symbol creates single-line comments in Python, allowing developers to add explanatory notes without affecting code execution. The example demonstrates two common commenting patterns: standalone comments that occupy their own line and inline comments that follow code on the same line.

Single-line comments serve several key purposes in maintaining readable code:

  • Explaining complex logic or non-obvious implementation details
  • Documenting temporary code changes or marking areas for future updates
  • Breaking up long code sections into logical chunks
  • Providing context for other developers who may work with the code

Basic commenting techniques

Beyond single-line comments with #, Python offers several powerful techniques for documenting code blocks and adding contextual notes to your programs.

Using multiple # symbols for multi-line comments

# This is the first line of a multi-line comment
# This is the second line
# This is the third line
print("Multiple line comments using hash symbols")
Multiple line comments using hash symbols

When you need to write longer explanatory comments that span multiple lines, you can add the # symbol at the start of each line. This creates a visually consistent block of documentation that's easy to read and maintain.

  • Each line must start with its own # symbol
  • The comment block remains readable in most code editors thanks to consistent indentation
  • You can quickly comment or uncomment individual lines while debugging

While Python doesn't have a native multi-line comment syntax like some other languages, this approach offers flexibility. You can expand or contract the comment block by adding or removing lines—each marked with #—without affecting the surrounding code structure.

Using triple quotes for multi-line comments

"""
This is a multi-line comment using triple quotes.
Python technically treats this as a string, but if it's not
assigned to a variable, it's ignored by the interpreter.
"""
print("Multi-line comment using triple quotes")
Multi-line comment using triple quotes

Triple quotes (""") offer a cleaner alternative for writing multi-line comments in Python. While technically creating a string literal, Python's interpreter ignores these triple-quoted blocks when they're not assigned to variables.

  • Triple quotes preserve line breaks and indentation exactly as written
  • You don't need to add comment symbols to each line
  • They work well for temporary code commenting during debugging

Many developers use triple quotes for docstrings—Python's built-in documentation format. When placed at the start of a module, class, or function, these comments become accessible through Python's help system.

Adding inline comments after code

name = "Python"  # Assign the string "Python" to variable 'name'
age = 30         # Assign the number 30 to variable 'age'
print(f"{name} is approximately {age} years old")
Python is approximately 30 years old

Inline comments provide immediate context for specific code lines. They follow the code on the same line, separated by the # symbol and at least two spaces for clarity.

  • Position inline comments at a consistent indentation level to maintain readability. Notice how the comments in the example align vertically despite different code lengths
  • Keep inline comments brief and focused on explaining the "why" rather than restating the obvious "what" the code does
  • Use them strategically for variables or operations that might not be immediately clear to other developers

The example demonstrates clean inline commenting by explaining the purpose of each variable assignment while maintaining consistent spacing and alignment. This practice makes the code more maintainable without cluttering it with excessive documentation.

Advanced commenting techniques

Python's advanced commenting capabilities extend beyond basic syntax to enable precise function documentation, type specifications, and selective code execution control—features that help developers write more maintainable and self-documenting code.

Using docstrings for function documentation

def greet(name):
    """
    This function greets the person passed in as a parameter.
    
    Args:
        name (str): The name of the person to greet
    """
    print(f"Hello, {name}!")

greet("Python developer")
Hello, Python developer!

Docstrings provide standardized documentation for Python functions, making code easier to understand and maintain. The triple-quoted string directly after the function definition serves as built-in documentation that developers can access through Python's help system.

  • The docstring explains the function's purpose and lists expected parameters with their types
  • Python's built-in tools can extract these docstrings to generate automatic documentation
  • Following a consistent format helps other developers quickly understand how to use your functions

In the example, the docstring for greet() clearly states that it takes a string parameter name and describes the function's greeting behavior. This documentation style proves especially valuable when working on larger projects or sharing code with other developers.

Type hinting with comments

def calculate_area(radius):  # type: (float) -> float
    """Calculate the area of a circle with the given radius."""
    return 3.14159 * (radius ** 2)

area = calculate_area(5)
print(f"Area: {area}")
Area: 78.53975

Type hints in comments help Python developers specify expected data types for function inputs and outputs. The comment # type: (float) -> float indicates that calculate_area() takes a floating-point number as input and returns another float.

  • Type hints improve code readability by making data types explicit without enforcing strict type checking
  • This commenting style works well with older Python versions that don't support modern type annotations
  • Tools like mypy can analyze these comments to catch potential type-related bugs before runtime

While modern Python offers built-in type hinting syntax, comment-based hints remain useful for maintaining backward compatibility or working with legacy codebases. They provide the same documentation benefits without requiring newer Python features.

Using comments to disable code blocks

print("This line will execute")

'''
print("This line is commented out")
print("This line is also commented out")
'''

# print("This single line is commented out")
This line will execute

Comments help you temporarily disable code without deleting it. This technique proves invaluable during debugging or when testing different implementation approaches. The example demonstrates two common methods: using triple quotes (''') to comment out multiple lines and the # symbol for single-line code disabling.

  • Triple quotes effectively create a multi-line string that Python's interpreter ignores. This approach works well when you need to disable larger code blocks
  • The # symbol offers quick control for individual lines. It's perfect for temporary tweaks or comparing different versions of a single statement
  • Both methods preserve the original code. You can easily re-enable it by removing the comment syntax

Many developers keep commented-out code as reference points or fallback options during development. However, consider removing these comments before pushing to production to maintain clean, readable codebases.

Using comments to explain data transformations

Comments play a crucial role when transforming raw data into structured formats, helping developers track complex parsing operations and data flow through their programs.

# Convert CSV-like string into a structured data dictionary
raw_data = "John,Doe,35,Developer;Jane,Smith,28,Designer;Bob,Johnson,42,Manager"

# Split data by person (semicolon delimiter) and then by attributes (comma delimiter)
people = []
for person_data in raw_data.split(';'):
    # Each person's data is in the format: firstname,lastname,age,profession
    attrs = person_data.split(',')
    people.append({
        'first_name': attrs[0],
        'last_name': attrs[1],
        'age': int(attrs[2]),
        'profession': attrs[3]
    })

print(f"Processed {len(people)} people:")
print(people[0])  # Print the first person's data

This code transforms a string containing semicolon-separated records into a structured list of dictionaries. Each record represents a person's information, with individual fields separated by commas.

The code uses split() twice: first with ';' to separate individual records, then with ',' to extract each person's attributes. It creates a dictionary for each person, mapping their data to specific keys like first_name and age. The int() function converts the age string to a number.

The final output is a list of dictionaries. Each dictionary contains four key-value pairs that make the data easier to access and manipulate programmatically. This pattern is common when parsing CSV-style data or converting between different data formats.

Using comments to document configuration options in an application

Comments provide essential documentation for application configuration settings, helping developers understand available options and their default values while making the codebase more maintainable.

def initialize_app(config):
    """Initialize application with the provided configuration."""
    # Database settings - controls connection parameters
    db_host = config.get('db_host', 'localhost')  # Default to localhost if not specified
    db_port = config.get('db_port', 5432)  # Default PostgreSQL port
    
    # Feature flags - enable/disable specific functionality
    enable_logging = config.get('enable_logging', True)  # Logging on by default
    debug_mode = config.get('debug_mode', False)  # Debug off by default
    
    print(f"App initialized with: DB={db_host}:{db_port}, Logging={enable_logging}, Debug={debug_mode}")

# Sample configuration
app_config = {'db_host': 'production.db', 'debug_mode': True}
initialize_app(app_config)

The initialize_app() function sets up a Python application using a dictionary of configuration settings. It handles two key aspects of the application setup:

  • Database connection settings with sensible defaults: localhost for the host and port 5432 for PostgreSQL
  • Application behavior flags that control logging and debugging functionality

The function uses Python's dictionary get() method to retrieve configuration values. This approach provides fallback defaults when a setting isn't specified in the config dictionary. The example demonstrates this by passing app_config with only two settings—the function automatically uses default values for the unspecified options.

Common errors and challenges

Python's commenting system can trip up both new and experienced developers through syntax mistakes, incorrect comment styles, and accidental code disabling.

Developers often forget to properly close triple-quoted comments with matching """ delimiters. This causes Python to treat the rest of the file as part of the comment, preventing code execution. The solution is simple: always ensure your opening and closing triple quotes match.

Another common pitfall comes from developers with experience in other programming languages who try to use // or /* */ comment styles in Python. These syntaxes don't work in Python. The language only recognizes # for single-line comments and triple quotes for multi-line comments or docstrings.

  • Always use # for single-line comments
  • Use triple quotes for multi-line comments and documentation
  • Never mix comment styles from other languages

Perhaps the most frustrating challenge occurs when developers accidentally comment out essential code with # symbols. This typically happens during debugging sessions when commenting out multiple lines for testing. Modern code editors help prevent this by highlighting commented code in different colors. Regular code reviews also help catch these issues before they reach production.

  • Use clear visual indentation to distinguish active code from comments
  • Review commented sections carefully before committing changes
  • Consider using version control instead of commenting out large code blocks

Forgetting to close triple-quoted """ comments properly

Unclosed triple-quoted comments create a particularly frustrating Python error. When you forget to add the closing """, Python treats all subsequent code as part of the comment block, preventing execution of what should be active code. The example below demonstrates this common mistake.

"""
This comment block is not closed properly
print("This line won't execute")
print("Neither will this one")

print("This line also won't execute")

Without the closing """, Python's interpreter reads the entire file as a single comment block. The code below demonstrates the proper way to structure triple-quoted comments.

"""
This comment block is properly closed
"""
print("This line will execute")
print("This line will also execute")

The solution demonstrates proper triple-quote closure with matching """ delimiters. This ensures Python correctly identifies the comment block's boundaries and executes the subsequent code. The interpreter treats everything between the opening and closing triple quotes as a comment while running the remaining lines normally.

  • Always check that triple quotes appear in pairs
  • Use your code editor's syntax highlighting to spot unclosed comments
  • Watch for unexpected behavior where code seems to "disappear" during execution

This issue commonly surfaces during rapid development or when copying code snippets. Modern IDEs help prevent it by automatically adding closing quotes. However, developers should still manually verify proper comment closure before running their code.

Using // or /* */ comment styles in Python

Developers transitioning from languages like C++ or JavaScript often try to use // for single-line comments and /* */ for multi-line comments in Python. These familiar syntax patterns from other languages will trigger immediate syntax errors in Python code.

// This is not a valid Python comment - it's from C/Java/JavaScript
print("This will cause a syntax error")

/* This multi-line comment style
   doesn't work in Python either */
print("More syntax errors")

Python's interpreter encounters a SyntaxError when it finds these C-style comment markers. The forward slashes and asterisks have no special meaning in Python's syntax. Let's examine the correct Python commenting approach in the following example.

# This is the correct Python single-line comment
print("This will work correctly")

"""
This is the proper way to do
multi-line comments in Python
"""
print("No syntax errors now")

The corrected code demonstrates Python's proper commenting syntax. Using # for single-line comments and triple quotes (""") for multi-line comments ensures your code runs without syntax errors. Python's interpreter recognizes these specific markers while ignoring other commenting styles.

  • Watch for this issue when copying code from other languages
  • Pay attention to your IDE's syntax highlighting
  • Remember that Python only accepts # and triple quotes for comments

Modern code editors help catch these syntax errors by highlighting invalid comment markers. They often include auto-completion features that insert the correct Python comment syntax automatically.

Accidentally commenting out critical code with #

Developers often accidentally comment out essential code while debugging or testing alternatives. This common mistake happens when using the # symbol to temporarily disable code blocks. The commented-out lines prevent the function from executing its intended logic, leading to unexpected None returns or broken functionality.

def process_data(value):
    # result = value * 2
    # Apply additional processing
    # return result
    
    print("Processing complete")

print(process_data(5))  # Will return None, not the expected value

The process_data() function returns None because all calculation logic sits inside commented lines. Only the print statement remains active. The code below demonstrates the proper implementation with working calculations.

def process_data(value):
    result = value * 2
    # Apply additional processing
    print("Processing complete")
    return result

print(process_data(5))  # Will return 10 as expected

The corrected process_data() function now properly calculates and returns a value instead of None. By uncommenting the calculation logic while keeping the debugging print statement, the function multiplies the input by 2 and returns the result.

  • Watch for accidentally commented core logic during debugging sessions
  • Use version control systems instead of commenting out large blocks of code
  • Pay attention to unexpected None returns. They often indicate commented-out return statements

Modern IDEs help prevent this issue by dimming commented code and providing keyboard shortcuts to quickly toggle comments. Regular code reviews also catch these oversights before they reach production environments.

FAQs

What is the difference between single-line and multi-line comments in Python?

Python offers two distinct comment styles for different documentation needs. Single-line comments start with # and help explain individual lines or brief notes. Multi-line comments use triple quotes """ or ''' to span multiple lines—these function as docstrings when placed at the start of functions or modules.

The key difference lies in their purpose. Single-line comments primarily serve developers maintaining code, while multi-line comments generate accessible documentation that Python tools can extract to create reference materials.

Can you use the hash symbol anywhere in a line to start a comment?

No, you can't place the # symbol anywhere in a line to start a comment. Comments must begin at the start of a line or after whitespace. The Python interpreter reads code line by line from left to right—it needs clear signals about where code ends and comments begin. This prevents ambiguity in expressions like total#items which could be misinterpreted as a comment rather than a variable name.

This design choice makes Python code more readable and predictable. It eliminates confusion about whether symbols within expressions might accidentally trigger comments.

Do comments affect the performance of Python programs when they run?

Comments don't affect Python program performance. The Python interpreter removes comments during the compilation phase, converting source code into bytecode. When you run a Python script, the interpreter first parses the code and strips out all text following the # symbol or enclosed in """ multi-line strings marked as comments.

This means your comments—whether they're short inline notes or extensive documentation—add zero overhead to the program's execution. The bytecode runs exactly the same way regardless of how many comments you include.

Is there a way to temporarily disable multiple lines of code without deleting them?

Yes, you can temporarily disable multiple lines of code using comment syntax. The most common methods include using /* */ for multi-line comments or adding // before each line. Comments prevent code execution while preserving it for future reference—this practice is called "commenting out" code.

Developers often use this technique during debugging to isolate issues or when testing alternative implementations. Modern IDEs streamline this process with keyboard shortcuts: select the code and press Ctrl+/ or Cmd+/ to toggle comments.

What happens if you put a comment inside a string in Python?

Comments inside Python strings become part of the string itself. Python treats everything between quotation marks as literal text, including what would normally be comment syntax. For example, if you write "Hello #this is a comment", Python includes the entire text as part of the string value.

This behavior makes sense because strings often need to contain special characters like # for practical purposes—think of URLs, markdown text, or code examples that you're storing as strings.

🏠