Sunday, October 25, 2020

Docstrings and Comments in Python

Docstrings is used for documenting the code in python. Doc strings are literal strings at the beginning used for documenting a module or function . We use triple quoted strings for single line and multi line documentation strings and even add more detail.

Paste the below code into a file named docstring.py

"""
   Reads a number and returns even or odd
   
    Usage:
        python docstring.py <number>
"""

import sys

def even_or_odd(n):
    """
        Evaluates if a passed number is even or odd
        
    Args:
        Takes one argument as number
    Return:
        returns the result even or odd
    """
    if(n%2 == 0):
        print("Even")
    else:
        print("Odd")

def main(x):
    """Calls even_or_odd function passing the argument
    """
    even_or_odd(x)
    
if "__name__" == "__main__":
    main(sys.argv[1])

Download the code from GitHub

After copying the above code into a file, import the file and run help(docstring) we will see a nice documentation of our module.

Comments in python start with hash symbol #. Often in code we need to explain what approach is followed to achieve the required functionality.
Begin with # symbol and continue till end of line

if "__name__" == "__main__":
    main(sys.argv[1]) # passing a command line argument


1 comment:

  1. Nice knowledge gaining article. This post is really the best on this valuable topic.
    cs代写

    ReplyDelete

Operations on Python Dictionaries