Practical – 153 : Document code segments using comments and documentation strings

1. Single-line Comments

Use # for brief explanations.

# This is a single-line comment

name = “Saiyam”  # Assigning a string to the variable ‘name’

2. Multi-line Comments

Python doesn’t have built-in multi-line comments, but multiple single-line # work:

# This program adds two numbers

# and displays the result

3. Docstrings (Documentation Strings)

Use triple quotes (“”” “”” or ”’ ”’) to document functions, classes, or modules.

🔹 Function with docstring:

def add(a, b):

    “””

    This function takes two numbers

    and returns their sum.

    “””

    return a + b

🔹 Accessing docstring:

print(add.__doc__)

Full Example: Documented Python Program

“””

Program: Calculator Example

Author: Saiyam

Date: 2025-06-06

Description: This program demonstrates documentation,

comments, and basic arithmetic operations in Python.

“””

# Function to add two numbers

def add(x, y):

    “””Returns the sum of x and y”””

    return x + y

# Function to subtract two numbers

def subtract(x, y):

    “””Returns the difference of x and y”””

    return x – y

# Taking input from user

num1 = float(input(“Enter first number: “))  # User input

num2 = float(input(“Enter second number: “))

# Performing operations

print(“Addition:”, add(num1, num2))       # Print result

print(“Subtraction:”, subtract(num1, num2))

🔍 Why Use Comments and Docstrings?

Feature

Purpose

# comment

Explain a line/block of code

Docstrings

Explain what a function/class/module does

Good practice

Makes code readable for others and for future updates