Doc strings in Python

In the object oriented example, you might have noticed a sentence enclosed in triple double quotes:

    """A Python class to store student information"""

This is called a doc string. The doc string is used to document information about a class or a method. Doc strings are especially helpful while trying to store information related to the usage of a method or a class (this will be demonstrated later in this chapter). Doc strings are also used at the beginning of a file to store multi-line comments related to an application or a code sample. Doc strings are ignored by the Python interpreter and they are meant to provide documentation about a class to fellow programmers.

Similarly, the Python interpreter ignores any single line comment that starts with a # sign. Single line comments are generally used to make a specific note on a block of code. The practice of including well-structured comments makes your code readable.

For example, the following code snippet informs the reader that a random number between 0 and 9 is generated and stored in the variable rand_num:

# generate a random number between 0 and 9 
rand_num = random.randrange(0,10)

On the contrary, a comment that provides no context is going to confuse someone who is reviewing your code:

# Todo: Fix this later

It is quite possible that you may not be able to recall what needs fixing when you revisit the code later.