Comments python

Comments in Python

Comments are lines in a Python program that are ignored by the interpreter during execution. They are used to explain the code, improve readability, and provide additional information for anyone reading the code.

Why Use Comments?

  • Improve code readability

  • Explain logic or provide metadata

  • Temporarily disable code

  • Include references or resources


Types of Comments in Python

Python supports three main types of comments:

  1. Single-Line Comments

  2. Multi-Line Comments

  3. Docstring Comments


Single-Line Comments

A single-line comment begins with the # symbol. Anything after # on that line is ignored by the interpreter.

Example:

# This is a sample comment name = "blog" print(name)

Output:

blog

๐Ÿ‘‰ Single-line comments are ideal for short explanations or notes in the code.


Multi-Line Comments

Python does not have a dedicated syntax for multi-line comments. However, you can achieve this in two common ways:

a) Using Multiple # Symbols

Each line starts with #.

Example:

# This is a multiline comment # written using multiple hashtags # to explain something in detail. print("Multiline comments")

Output:

Multiline comments

Docstring Comments

Docstrings are string literals written using triple quotes (''' or """) placed right after a function, class, or module definition. They serve as documentation and can be accessed via the __doc__ attribute.

Example:

def multiply(a, b): """Multiplies the value of a and b""" return a * b # Print the docstring of multiply function
print(multiply.__doc__)

Output:

Multiplies the value of a and b

๐Ÿ‘‰ Docstrings are commonly used to describe what a function, method, or class does.


Summary

  • Use # for single-line comments.

  • Use multiple # symbols for multi-line comments.

  • Use docstrings (""") for documenting functions, classes, and modules.

๐Ÿ‘€Comments make your code easier to understand and maintain. They are especially valuable when collaborating with other developers or revisiting your own code after some time.

Popular Posts