Master AI & Build your First Coding Portfolio with SkillReactor | Sign Up Now

Lesson 2 - Basic Python Syntax

2.3 Comments

Comments are short notes that describe the purpose of a specific code block. In Python, comments are ignored during runtime, making them useful for documenting code without affecting its execution.

This practice becomes essential in team environments where multiple programmers collaborate on the same project, as it enhances code readability and understanding.

Types of Comments in Python:

  1. Single-line comments: These are used to add brief comments on a single line of code. For example:
# Initializing variable
x = 10
print(x)
  1. Multi-line comments (Docstrings): Python doesn't have traditional multiline comments. Instead, it uses triple quotes (""") primarily for docstrings, which are used to describe functions, classes, or modules. For instance:
"""
Function to add two numbers
Return value: integer
"""
def add_num(a, b):
    return a + b

print(add_num(5, 5))  # Outputs: 10

In this example, the docstring provides a description of the add_num function and its return value.

Using comments, especially docstrings, is considered a best practice in professional Python coding. It helps maintain code clarity and ensures that the code remains understandable even after some time has passed.