Back to Python
2026-03-057 min read

Python Comments

Learn Python Comments step by step with clear examples and exercises.

Why This Matters

In programming, comments play a crucial role in making code more understandable, maintainable, and debuggable. They help:

  1. Document your code: Explain what each part of the code does and why you wrote it that way.
  2. Debugging: Comments can help you understand the flow of your program and identify issues more easily.
  3. Collaboration: When working in a team, comments make it easier for others to understand your code and contribute effectively.
  4. Real-world scenarios: In projects with strict deadlines or large teams, clear comments are essential for ensuring everyone is on the same page.
  5. Accessibility: Comments can help people with diverse backgrounds or different levels of programming expertise understand the code more easily.
  6. Compliance and transparency: Some organizations require comments to ensure compliance with coding standards and promote transparency in their codebase.
  7. Historical records: Comments can serve as a historical record of changes made to the code over time, making it easier for future developers to understand the evolution of the project.
  8. Reducing cognitive load: Well-written comments can help reduce the mental effort required to understand complex logic, making your code more approachable and easier to read.

Prerequisites

Before diving into Python comments, you should have a basic understanding of:

  1. Python syntax: Variables, data types, operators, and control structures like if-else statements and loops.
  2. Basic file handling: Know how to create, read, write, and append files in Python.
  3. Familiarity with Python's standard library: Understanding common libraries and modules can help you make the most of comments when documenting your code.
  4. Programming best practices: A good understanding of coding standards, design patterns, and testing methodologies will help you write cleaner, more maintainable code.

Core Concept

Python uses two types of comments:

  1. Single-line comments (#)
  2. Multi-line comments (triple quotes """ or ''')

Single-line Comments

To create a single-line comment in Python, simply start the line with a hash symbol (#). Everything after the hash on that line will be ignored by the interpreter:

print("Hello, World!") # This is a single-line comment.

Multi-line Comments

For multi-line comments, you can use triple quotes (either """ or '''). These can span multiple lines:

"""
This is a
multi-line comment.
You can write as many lines as needed.
"""

'''
Another example of a multi-line comment.
These are also useful for documenting large sections of code.
'''

Commenting Best Practices

  1. Be concise: Keep comments brief and to the point, focusing on explaining complex logic or providing context.
  2. Use proper grammar and spelling: Well-written comments make your code more professional and easier to understand.
  3. Avoid using abbreviations: Abbreviations can be confusing and hard to understand for people who are not familiar with them.
  4. Explain the purpose, not the implementation: Comments should help others understand what your code does, not how it works.
  5. Use comments sparingly: Overcommenting can make the code harder to read and understand.
  6. Comment on changes: When making significant changes or modifications to existing code, update the comments to reflect those changes.
  7. Document complex functions and classes: Longer functions and classes should have a brief summary at the top explaining their purpose and any important details about how they work.

Worked Example

Let's create a simple Python script that calculates the sum of all numbers from 1 to 10 using comments to explain each step:

Define a function to calculate the sum of numbers from start to end (inclusive)

def sum_numbers(start, end):

Base case: if start is equal to end, return the start value as the sum

if start == end:

return start

else:

Recursive call: add the current number to the result of calling the function with the next numbers

result = start + sum_numbers(start + 1, end)

Return the calculated sum

return result

Get user input for the starting and ending numbers

start = int(input("Enter the starting number: "))

end = int(input("Enter the ending number: "))

Check if the numbers are valid (positive integers)

if start <= 0 or end <= 0:

print("Invalid input. Please enter positive integers.")

else:

Calculate the sum using the defined function

result = sum_numbers(start, end)

Print the result with a comment explaining what it is

print("# The sum of numbers from", start, "to", end, "is:", result)

Common Mistakes

  1. Forgetting to add comments: Don't underestimate the importance of documenting your code.
  2. Overusing comments: Too many comments can make the code harder to read and understand.
  3. Incorrectly formatting comments: Make sure you use the correct syntax for single-line and multi-line comments.
  4. Not explaining the purpose of each section or function: Comments should help others understand what your code does, not just how it works.
  5. Using comments instead of proper variable names: Use clear and descriptive variable names to make your code self-explanatory.
  6. Commenting on obvious or simple parts of the code: Comments should be used for complex logic or providing context, not for explaining trivial parts of the code.
  7. Not updating comments when making changes: Keep comments up-to-date to reflect changes in the codebase.
  8. Using outdated or incorrect information in comments: Ensure that comments are accurate and relevant to the current state of the code.
  9. Ignoring the importance of comments during code reviews: Encourage team members to review comments as part of the code review process to ensure they are clear, concise, and helpful.
  10. Neglecting to document new features or changes: When adding new features or making changes to existing code, make sure to update the comments accordingly.

Practice Questions

  1. Write a Python script that calculates the product of all numbers from 1 to 10 using comments to explain each step.
  2. Modify the sum_numbers function from the worked example to handle negative numbers and calculate the sum of all numbers between the two input numbers (inclusive).
  3. Write a Python script that reads a list of numbers from a file, calculates their average, and writes the result back to the file using comments to explain each step.
  4. Create a function that finds the largest prime number in a given range using comments to explain each step of the algorithm.
  5. Write a Python script that generates Fibonacci numbers up to a specified number (inclusive) using comments to explain each step.
  6. Modify the sum_numbers function from the worked example to handle floating-point numbers and calculate the sum of all numbers between two input numbers (inclusive).
  7. Write a Python script that reads a list of strings from a file, sorts them alphabetically, and writes the result back to the file using comments to explain each step.
  8. Create a function that finds the smallest common multiple of two numbers using comments to explain each step of the algorithm.
  9. Write a Python script that calculates the factorial of a number entered by the user using comments to explain each step, including handling negative numbers and large factors.
  10. Modify the sum_numbers function from the worked example to handle floating-point numbers and calculate the sum of all numbers between two input numbers (exclusive).

FAQ

What is the purpose of comments in Python?

  • Comments help make code more understandable, maintainable, and debuggable by providing explanations for complex logic or context. They can also aid collaboration and compliance with coding standards.

How do I create a single-line comment in Python?

  • To create a single-line comment in Python, start the line with a hash symbol (#). Everything after the hash on that line will be ignored by the interpreter.

How do I create a multi-line comment in Python?

  • For multi-line comments, you can use triple quotes (either """ or '''). These can span multiple lines.

What are some best practices for using comments in Python?

  • Some best practices include being concise, using proper grammar and spelling, avoiding abbreviations, explaining the purpose of each section or function, using comments sparingly, commenting on changes, documenting complex functions and classes, and updating comments when making changes.

Why is it important to use comments in Python?

  • Using comments in Python is important because they help make code more understandable, maintainable, and debuggable. They can also aid collaboration, compliance with coding standards, and promote transparency in the codebase. Additionally, comments serve as historical records of changes made to the code over time, making it easier for future developers to understand the evolution of the project.
Python Comments | Python | XQA Learn