Python Basics Tutorial – Comments in Python

Comments in Python

Comments in python are text that helps make the code more understandable. Python is quite a naturally readable language. Be sure not to just repeat code in the comments section. Remember the comments you write now may help you or some one else understand your code in the future.

# Single Line Comment

''' Multi line 
    Comment
     '''

""" Docstring Comment. Can be single or multi-lined
    https://en.wikibooks.org/wiki/Python_Programming/Source_Documentation_and_Comments
"""

print("*** Comments ***\nSingle Line: # \nMultiline: '''\n")

Inline Comments

Comments that appear on the same line as code are referred to as inline comments. It is best not use comments like this. Unless you are describing something obscure that can’t be gleaned from the code.

c = 299792458 #Speed of Light m/s

DocStrings

The simple example below is taken from the wiki book on Python Programming.

#!/usr/bin/env python
# docstringExample.py

""" Example of using documentation strings.
    Source: https://en.wikibooks.org/wiki/Python_Programming/Source_Documentation_and_Comments
"""

class Knight:
    """
    An example class.
    
    Call spam to get bacon.
    """
    
    def spam(eggs="bacon"):
        """Prints the argument given."""
        print(eggs)

# to get documentation $ pydoc docstringExample.py

After we run pydoc in the Terminal we get:

pydoc DocString Terminal

As Python is such readable language the need for comments is minimal.

Leave a Reply