KnowledgeBoat Logo

Computer Science

What are docstrings ? What is their significance ? Give example to support your answer.

Python Libraries

2 Likes

Answer

The docstrings are triple quoted strings in a Python module/program which are displayed as documentation when help (<module-or-program-name>) command is displayed.

Significance of docstrings is as follows:

  1. Documentation — Docstrings are used to document Python modules, classes, functions, and methods.
  2. Readability — Well-written docstrings improve code readability by providing clear explanations of the code's functionality.
  3. Interactive Help — Docstrings are displayed as documentation when help (<module-or-program-name>) command is displayed.

For example:

# tempConversion.py
"""Conversion functions between fahrenheit and centigrade"""

# Functions
def to_centigrade(x):
    """Returns: x converted to centigrade"""
    return 5 * (x - 32) / 9.0

def to_fahrenheit(x):
    """Returns: x converted to fahrenheit"""
    return 9 * x / 5.0 + 32

# Constants
FREEZING_C = 0.0  #water freezing temp.(in celcius)
FREEZING_F = 32.0  #water freezing temp.(in fahrenheit)
import tempConversion
help(tempConversion)
Output
Help on module tempConversion:

NAME
    tempConversion-Conversion functions between fahrenheit and centigrade
FILE
    c:\python37\pythonwork\tempconversion.py
FUNCTIONS
    to_centigrade(x)
        Returns : x converted to centigrade
    to_fahrenheit(x)
        Returns : x converted to fahrenheit
DATA 
    FREEZING_C = 0.0
    FREEZING_F = 32.0

Answered By

1 Like


Related Questions