This post provides a quick tutorial on how to comment Python code.
There are three ways of commenting Python code:
- Single-line comments
- Multi-line comments
- Docstring comments
In Python, single-line comments can be implemented with the # operator. This is demonstrated in the example below.
# this comment could describe what the variables below represent a = 1 b = 3.3
Multi-line Python comments can be implemented with “”” “””. I show this in the example below:
""" FUNCTION DESCRIPTION: This function takes two input parameters, multiplies them and returns the result input: (int) par1, (float) par2 returns: (float) multiplication result """ def multiplier(par1,par2): return(par1*par2)
Let us quickly test the function:
Docstring comments are another type of Python comments. By convention, docstring comments are used to document functions. More precisely, docstring comments are used to describe and document what a function does – i.e. what its effect is, rather than describing its internal procedures and decision making.
In Python, docstring comments are also used to describe classes and methods.
Docstring comments have to be declared right after the function, class or method declaration. They are implemented with triple quotes (“”” “””). Here is an example:
def multiplier(par1,par2): """ function returns multiplication result of its inputs """ return(par1*par2)
We can access docstring comments in two ways:
- We can call the __doc__ method of the object
- We can use the help function
Here is how we can access the docstring comment by calling the __doc__ method:
' function returns multiplication result of its inputs '
We can e.g. print this comment:
function returns multiplication result of its inputs
And here is how we can use the help() function fo access docstring comments:
Help on function multiplier in module __main__: multiplier(par1, par2) function returns multiplication result of its inputs
Data scientist focusing on simulation, optimization and modeling in R, SQL, VBA and Python