How to comment in Python

Learn to comment in Python with our guide. Explore methods, tips, real-world uses, and how to debug common errors.

How to comment in Python
Published on: 
Thu
Feb 5, 2026
Updated on: 
Tue
Feb 24, 2026
The Replit Team Logo Image
The Replit Team

Python comments are essential tools for code readability and documentation. They allow you to explain your logic to other developers and your future self, which simplifies maintenance and collaboration.

You will learn different comment techniques and best practices. The article covers real-world applications and tips to use comments for effective debugging, so you can write cleaner, more professional code.

Using the # symbol for single-line comments

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

The hash symbol (#) tells the Python interpreter to ignore everything that follows it on the same line. This makes it perfect for leaving notes in your code. The example demonstrates two common placements for these comments.

  • Full-line comments: Placing a # at the start of a line, like # This is a simple comment in Python, is ideal for explaining the purpose of the code block that comes next.
  • Inline comments: Adding a comment after your code, such as on the print() line, lets you clarify what that specific line does without disrupting the code's flow.

Basic commenting techniques

Beyond single-line notes with the # symbol, Python offers a couple of ways to write more extensive, multi-line comments for detailed explanations.

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")--OUTPUT--Multiple line comments using hash symbols

For longer explanations, you can create a multi-line comment by starting each line with a # symbol. While Python doesn't have a dedicated multi-line comment syntax, this approach is the standard convention and is recommended by the official PEP 8 style guide.

  • This method keeps your comments clean and easy to read, especially when you need to detail a complex function or a tricky piece of logic before the code itself.

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")--OUTPUT--Multi-line comment using triple quotes

You can also use triple quotes—either """ or '''—to create what functions as a multi-line comment. Python technically treats this block as a multi-line string. Since it isn't assigned to a variable, the interpreter simply ignores it during execution.

  • While this method works for comments, its primary purpose is for writing docstrings, which are special strings used to document modules, functions, classes, and methods.

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")--OUTPUT--Python is approximately 30 years old

Inline comments are perfect for adding quick notes right next to your code. As shown in the example, you can use them to explain variable assignments like name = "Python" or age = 30. This helps clarify the purpose of a variable, especially when its name isn't self-explanatory.

  • For clean formatting, the PEP 8 style guide suggests leaving at least two spaces between your code and the comment.
  • They're best used for small clarifications. For more complex logic, a full-line comment before the code block is often a better choice.

Advanced commenting techniques

Once you're comfortable with basic notes, you can use comments for more advanced tasks like documenting functions, adding type hints, and debugging 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")--OUTPUT--Hello, Python developer!

Docstrings are more than just comments—they're a built-in way to document your functions. You place a triple-quoted string immediately after the def line, as seen in the greet function example. This string becomes the function's official documentation, explaining its purpose to anyone who uses it.

  • It typically includes a summary of what the function does, along with details about its parameters, often under a section like Args:.
  • Unlike regular comments, you can access docstrings programmatically using tools like help(greet) or by printing the function's __doc__ attribute.

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}")--OUTPUT--Area: 78.53975

Before modern type annotation syntax was introduced in Python 3.5, developers used specially formatted comments for type hinting. This method is still supported for backward compatibility. The comment # type: (float) -> float on the calculate_area function line is a perfect example of this older style.

  • The (float) part specifies that the radius parameter is expected to be a floating-point number.
  • The -> float indicates that the function should return a float value.

These hints don't affect runtime execution, but they allow static analysis tools and IDEs to catch potential type-related bugs before you run the code.

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")--OUTPUT--This line will execute

Commenting out code is a powerful debugging technique that lets you temporarily disable parts of your script without deleting them. The example shows how you can use both comment types to prevent lines from running while you test your program.

  • Triple quotes (''') are great for quickly disabling a large block of code, like the two print() statements.
  • The hash symbol (#) is perfect for commenting out a single line, such as # print("This single line is commented out").

This approach helps you isolate bugs or experiment with different logic safely.

Move faster with Replit

Replit is an AI-powered development platform that transforms natural language into working applications. You can describe what you want to build, and Replit Agent creates it—complete with databases, APIs, and deployment.

The commenting techniques you've learned, from simple notes to complex docstrings, are foundational. Replit Agent can take these concepts and help you build production-ready tools:

  • A documentation generator: Build a tool that automatically parses Python scripts and generates clean, web-based documentation from your docstrings.
  • A legacy code linter: Create a static analysis tool that reads comment-based type hints to help you modernize and ensure type safety in older Python codebases.
  • An interactive code debugger: Deploy a web application that teaches debugging by guiding users through a script, showing them how to use comments to isolate and fix bugs.

Turn your own ideas into reality. Describe your next project and let Replit Agent write the code, test it, and handle deployment, all from your browser.

Common errors and challenges

While comments are helpful, a few common mistakes can lead to syntax errors or unintended behavior in your code.

Forgetting to close triple-quoted """ comments properly

Forgetting to close a triple-quoted comment is a frequent error. When you open a comment with """ but don't add a closing """, the Python interpreter thinks everything that follows is part of a long string. This often causes a SyntaxError much later in your script, making the bug tricky to find.

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

Another common pitfall is using comment styles from other languages. If you're coming from JavaScript or C++, you might be tempted to use // for single-line comments or /* */ for block comments. Python doesn't recognize these, so using them will result in a SyntaxError.

Accidentally commenting out critical code with #

It's also easy to accidentally comment out essential code with the # symbol, especially during debugging. You might temporarily disable a line to test something and then forget to remove the #. This can lead to silent failures where your program runs without errors but doesn't produce the correct result because a critical piece of logic was never executed.

Forgetting to close triple-quoted """ comments properly

An unclosed triple-quoted comment can make your script grind to a halt. If you start a block with """ and forget to end it, Python gets confused and reads all the code that follows as plain text, triggering a SyntaxError. See what happens in the code below.

"""
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")

Since the opening """ is never closed, the interpreter treats the following print() functions as plain text. It reaches the end of the file while still inside the string, causing a SyntaxError. See the corrected version below.

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

By adding the closing """, you signal to the interpreter that the multi-line string is complete. This allows the following print() functions to be recognized and executed as code. This error often pops up when you're temporarily commenting out large sections for debugging, so it's a good habit to double-check that your triple-quoted blocks are always properly closed before running your script.

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

If you code in languages like C++ or JavaScript, it's easy to accidentally use their comment styles in Python. Python doesn't understand // for single lines or /* */ for blocks, which immediately causes a SyntaxError. See what happens in the code below.

// 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")

The interpreter attempts to execute // and /* as code. Since they aren't valid Python syntax, the program crashes. The corrected example below shows how to write these comments properly.

# 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")

By replacing `//` and `/* */` with Python's correct syntax, the errors are resolved. The interpreter now correctly identifies the single-line comment starting with `#` and the multi-line block enclosed in `"""..."""`, allowing the code to run. It's a common slip-up for developers who switch between Python and languages like JavaScript or C++, so be mindful of your comment style when changing contexts to avoid these simple syntax errors.

Accidentally commenting out critical code with #

It's easy to accidentally leave a # in front of important code, especially during debugging. This mistake can cause silent failures where your program runs without errors but produces the wrong output because a key step was skipped. See this problem in action below.

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

In the process_data function, the lines that calculate and return the result are commented out. Because there's no active return statement, the function finishes and implicitly returns None. See the corrected code below.

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

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

By uncommenting the result = value * 2 and return result lines, the process_data function now executes its core logic. The function correctly calculates and returns the value, so the final print statement outputs 10 instead of None. This kind of error is especially common after a debugging session, so it’s a good habit to review your changes and ensure no critical code remains disabled before you commit your work.

Real-world applications

Beyond avoiding common errors, effective comments are crucial for explaining complex logic in real-world applications like data transformations and application configurations.

Using comments to explain data transformations

When you're processing raw data, comments are crucial for explaining each step of the transformation, from parsing a messy string to organizing it into a clean, structured format.

# 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 example shows how to transform a single string of data into a more useful list of dictionaries. The code first uses split(';') to break the main string into individual records for each person.

  • A loop then processes each record, using split(',') to separate the attributes like name and age.
  • For each person, a new dictionary is created, mapping keys like 'first_name' to their corresponding values.
  • The age is converted from a string to a number with int(), making the data ready for further use.

Using comments to document configuration options in an application

In any application, comments are essential for documenting configuration options, making it clear what each setting controls and what its default value is.

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 demonstrates a flexible way to handle settings using the dictionary’s .get() method. This approach safely retrieves configuration values by providing a fallback if a key doesn't exist, which prevents your application from crashing.

  • The function looks for a key, such as 'db_host', in the provided config dictionary.
  • If the key isn't found, it automatically uses the default value you specify, like 'localhost'.

This allows you to override only the settings you need while letting others rely on their predefined defaults, making your configuration clean and manageable.

Get started with Replit

Turn your knowledge into a real tool with Replit Agent. Try prompts like, “Build a script that generates HTML docs from Python docstrings,” or “Create a linter that finds missing comments in my code.”

The agent writes the code, tests for errors, and deploys your app directly from your browser. Start building with Replit to bring your ideas to life.

Get started free

Create and deploy websites, automations, internal tools, data pipelines and more in any programming language without setup, downloads or extra tools. All in a single cloud workspace with AI built in.

Get started for free

Create & deploy websites, automations, internal tools, data pipelines and more in any programming language without setup, downloads or extra tools. All in a single cloud workspace with AI built in.