How to comment in Python

Master Python comments with our guide. Discover various methods, pro tips, real-world uses, and common error fixes for cleaner code.

How to comment in Python
Published on: 
Thu
Feb 5, 2026
Updated on: 
Mon
Apr 13, 2026
The Replit Team

Comments in Python are essential for code clarity and collaboration. They help explain complex logic, document your intentions, and make scripts more maintainable for yourself and other developers.

In this article, you'll explore techniques for effective comments and review best practices. You'll also find real-world applications and advice for debugging to help you write professional, understandable 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 # symbol signals the start of a comment, telling the Python interpreter to ignore the rest of the line. The example demonstrates two primary uses: dedicating an entire line to a comment or placing one after a line of code. Both are syntactically valid, but they serve different strategic purposes.

A full-line comment is best for explaining the ‘why’ behind a whole code block. An inline comment, however, is perfect for adding a quick note to a single statement that might otherwise be ambiguous. It’s a targeted way to clarify a specific piece of logic without disrupting the flow.

Basic commenting techniques

Building on the single-line # comment, you can also use several other fundamental techniques to document your code, from multi-line blocks to inline notes.

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

Unlike some languages, Python doesn't have a dedicated syntax for multi-line comments. The standard practice is to simply prefix each line with a # symbol. This creates a block that the interpreter ignores line by line, keeping your comments clean and readable.

  • It’s ideal for writing detailed explanations of functions or complex logic.
  • You can also use it to temporarily disable multiple lines of code for debugging—a common practice known as "commenting out," which is useful when iterating on code through vibe coding.

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

Another way to create multi-line comments is by using triple quotes, either """ or '''. While this technically creates a multi-line string, Python's interpreter ignores it if it isn't assigned to a variable—effectively making it function as a comment.

  • This technique is most often used for writing docstrings, which are built-in mechanisms for documenting modules, functions, and classes.
  • It allows you to write free-form text without prefixing every line with a # symbol.

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, like those shown in the example, sit on the same line as the code they describe. They're perfect for adding quick, targeted explanations to a single statement. Notice how a few spaces separate the code from the # symbol, which improves readability.

  • Add context, not noise. A good comment explains the ‘why’ behind your code, not just the ‘what’. For instance, explain why a variable is set to a specific value if it’s not immediately obvious.
  • Keep them brief. Inline comments should be short and to the point. If you need more space, a full-line comment is a better choice.

Advanced commenting techniques

Building on these fundamentals, comments unlock more powerful techniques for documenting functions, adding type hints, and managing your code during the debugging process.

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!

A docstring, or documentation string, is the triple-quoted string placed immediately after a function definition. In the greet example, it explains the function's purpose and details its parameters, like name. While it looks like a multi-line comment, it’s much more powerful.

Unlike regular comments, Python attaches the docstring to the function object itself. This means automated tools can use it to generate documentation, and developers can access it directly for help.

  • It serves as a standard way to describe what a function does.
  • It documents arguments (Args), return values, and other conventions.

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

In older Python versions, before modern type annotations became standard, developers used comments to specify types. The calculate_area function uses a special format, # type: (float) -> float, to declare that its radius parameter should be a float and that it will return a float, similar to patterns used when calculating area in Python.

  • The Python interpreter itself ignores this comment, but static type checkers and IDEs can read it.
  • This helps you catch potential type-related bugs before you even run the code, making your script more robust.

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 core debugging technique that lets you temporarily disable parts of your script without deleting them. The example shows how you can use both triple quotes and the hash symbol for this purpose, each with its own advantage.

  • Triple quotes (''' or """) are great for quickly disabling a multi-line block, which is helpful when you're trying to isolate a bug.
  • The # symbol is perfect for commenting out a single line, like # print("This single line is commented out"), for more targeted tests.

Move faster with Replit

Replit is an AI-powered development platform that comes with all Python dependencies pre-installed, so you can skip setup and start coding instantly. You won't need to configure environments, so you can just focus on the code.

Instead of piecing together techniques, you can describe the app you want to build and Agent 4 will take it from idea to working product. You can build practical tools that use the same logic covered in this article, like:

  • A geometry calculator that expands on the calculate_area function to find the area of multiple shapes.
  • A bulk message generator that uses a greet-style function to create personalized welcome emails for a list of new users.
  • A debugging assistant that helps you temporarily disable specific functions or code blocks to isolate issues in your script.

Simply describe your app, and Replit will write the code, test it, and fix issues automatically, all within your browser.

Common errors and challenges

Even with a simple feature like comments, a few common mistakes can trip you up and introduce bugs into your code.

Forgetting to close triple-quoted """ comments properly

It's easy to forget the closing triple quotes on a multi-line comment. When this happens, the Python interpreter continues to treat all subsequent code as part of the string, which often results in a SyntaxError and can unintentionally disable large portions of your script.

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

If you're coming from languages like JavaScript, C++, or Java, you might be tempted to use // for single-line comments or /* */ for block comments. Python doesn't recognize this syntax, so using them will immediately raise a SyntaxError and prevent your code from running.

Accidentally commenting out critical code with #

During debugging, it's common to use the # symbol to temporarily disable lines. However, you can easily forget to remove the # from a critical line of code, causing that logic to be skipped without any error message. This can lead to silent failures that are often tricky to track down.

Forgetting to close triple-quoted """ comments properly

Forgetting to close a triple-quoted """ comment is a common slip-up. The Python interpreter will keep reading everything that follows as part of an unfinished string, which can disable large sections of your code and usually triggers a SyntaxError.

Take a look at the example below to see this in action. Because the comment block isn't closed, none of the print statements will execute.

"""
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 initial """ is never closed, the interpreter never reaches the print statements. It considers them part of the comment, not executable code. The corrected version below shows how to resolve this.

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

By adding the closing """, you signal the end of the multi-line string, allowing the interpreter to correctly parse the print() statements as executable code. This error often happens when quickly commenting out large blocks for debugging. It’s a good practice to always double-check that your triple-quoted comments are properly terminated to avoid unexpected syntax errors.

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

Developers who switch between languages often carry over habits, like using // for single-line comments or /* */ for blocks. Python doesn't recognize this syntax, so it will immediately raise a SyntaxError. The code below shows what happens.

// 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 doesn't recognize // or /* */, so it reads them as invalid commands and throws an error. The example below shows how to resolve this with the correct syntax.

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

To fix the error, you'll need to use Python's native comment syntax. The hash symbol (#) is for single-line comments, while triple quotes (""") handle multi-line blocks. This is a common pitfall if you're coming from languages like JavaScript or C++, where // and /* */ are the norm. Sticking to Python's rules is the only way to avoid a SyntaxError and keep your script running.

Accidentally commenting out critical code with #

It's easy to forget to uncomment lines you've disabled with # during debugging. This mistake doesn't cause a crash but creates silent bugs where critical logic is skipped, leading to unexpected behavior. The code below shows this problem in action.

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 doesn't return a value because its return statement is commented out. It defaults to returning None, creating a silent bug. The corrected code below shows how to fix this.

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 correctly returns the calculated value instead of None. This fixes the silent bug. It's a common mistake to make during debugging, so always review your script after testing to ensure you haven't left critical logic disabled with a stray #. Learning proper techniques for uncommenting code in Python can help avoid these issues. Tools like code repair can help identify and fix such issues automatically.

Real-world applications

Beyond avoiding common errors, effective commenting is crucial for clarifying complex logic in real-world data transformations and application configurations.

Using comments to explain data transformations

Comments are invaluable when your code needs to parse and restructure raw data, such as converting a simple string into a more complex data dictionary.

# 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 script shows a practical way to parse a compact string into a structured list. It starts with raw_data, where records are separated by semicolons and attributes by commas. The goal is to create a clean list of dictionaries, making the data easier to work with.

  • The code first uses split(';') to isolate each person's data.
  • A for loop then iterates over these records, using split(',') to separate the details like name and age, demonstrating key techniques for splitting strings in Python.
  • Notice the int() function, which converts the age from a string to a number before storing it.

Using comments to document configuration options in an application

Comments are also critical for documenting an application’s configuration settings, helping developers understand default behaviors and how to manage features.

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)

This initialize_app function demonstrates a robust pattern for handling application settings. It takes a config dictionary and uses the .get() method to retrieve each setting. This is a safe way to handle configurations, as .get() supplies a default value if a specific setting isn't provided in the dictionary, preventing potential errors when accessing dictionaries in Python.

  • The code provides defaults for database connections and feature flags, like localhost or True for logging.
  • When called, the function uses the values from app_config where available but falls back on the defaults for any missing keys.

Get started with Replit

Turn your knowledge into a real tool. Give Replit Agent a prompt like “build a data parser with comments explaining the logic” or “create a settings manager with docstrings for each option.”

Replit Agent will write the code, test for errors, and help you deploy your app. You can focus on the idea, not the setup. Start building with Replit.

Build your first app today

Describe what you want to build, and Replit Agent writes the code, handles the infrastructure, and ships it live. Go from idea to real product, all in your browser.

Build your first app today

Describe what you want to build, and Replit Agent writes the code, handles the infrastructure, and ships it live. Go from idea to real product, all in your browser.