Technical Roadmap

Comments in Python

Comments are like sticky notes—short explanations written by a programmer to describe what the code is doing. These lines are not executed by the Python interpreter, meaning they have no effect on how your code runs.

You can write comments anywhere in a program: within a block of code, at the end of a line, or inside a complex expression to help you remember the logic behind that specific section.

💡 The Logicoria Tip

Think of comments like the side notes we write in our notebooks—they provide an explanation for the answers we’ve written.

Types of Comments in Python

There are two main ways to write a comment in Python:

1. Single-Line Comments

We can write a single-line comment using the hash character #. Anything written after the # on that same line will be ignored by the Python interpreter.

Python
# This variable stores the total count of our 200 articles
article_count = 24
print(article_count)
Output:
24

2. Multi-Line Comments

In Python, there isn't a specific symbol (like /* */ in other languages) for multi-line comments. Instead, we can use # on multiple lines or use Triple Quotes (""" or ''').

The Logicoria Tip

While triple quotes work for comments, the Official PEP 8 (Python's style guide) recommends using # for every line of a multi-line comment. Use triple quotes specifically for documenting what a function or class does!

i. Using # for Multi-Line

Python
# FILE: article_manager.py
# GOAL: To automate the upload of 100 articles.
# STATUS: Testing in Localhost (XAMPP).

print("Database logic initialized.")
Output:
Database logic initialized.

ii. Using """ (Triple Quotes)

Python
"""
FILE: article_manager.py
GOAL: To automate the upload of 100 articles.
STATUS: Testing in Localhost (XAMPP).
"""
print("Database logic initialized.")
Output:
Database logic initialized.

Questions & Answers:

  • 1. What is the main purpose of writing comments in code?
    Comments are used to explain what the code is doing so that programmers can understand the logic later.
  • 2. Does the Python interpreter execute the text written in comments?
    No, the interpreter ignores comments completely; they have no effect on the program's execution.
  • 3. Which symbol is used to create a single-line comment in Python?
    The hash character # is used for single-line comments.
  • 4. How can you create a multi-line comment according to PEP 8 guidelines?
    PEP 8 recommends using the # symbol at the beginning of every line in the multi-line block.
  • 5. What is the difference between using # and triple quotes (""") for comments?
    # is the standard for general comments, while triple quotes are often used for documenting specific functions or classes.
  • 6. Where in a program can you place a comment?
    You can place a comment anywhere, including at the end of a code line or on its own separate line.