Python Comments

  • Comments are the lines that are used to make your code more readable.
  • Comment lines are mainly used for documentation purposes to make the readers understand the source code.
  • These are the lines skipped during the program's execution by the compilers and the interpreters.
  • Sometimes, comments can also serve to prevent the execution of a line when testing code.
  • There are three types of comments in python.
    • Single line comments 
    • Multi-line comments
    • Docstring comments
Creating a comment:
1) Single line comment:
  • starts with the # (hashtag) symbol and extends till the end of the line.
  • While execution, Python will read and ignore these comment lines.
Python Comments
Single line comment
  • Single-line comments are mostly used for providing a short explanation for variables, functions, and logic expressions.
2) Multi-Line comment:
  • Python doesn't have a specific syntax for multi-line comments.
  • We can insert a # at the beginning for each line to make it a multi-line comment.
Python Comments
Multi-line comment using # (hashtag)
  • Or, we can start the line with ''(double quotes) / '''(Triple quotes) and ends with the same. This type of comment is also known as a multi-line string.
  • Since this multi-line string is not assigned to any variable, Python will read these lines and then ignores them.
Python Comments
Multi-line comment
  • In such a way, we can add multi-line comments in our codes and place our comments inside them.
3) Docstring comment: 
  • In Python, We have an in-built feature called Docstring.
  • The comments that appear right after the modules, functions, method, or class definitions are docstrings (documentation strings). 
  • We can access the docstring by using the __doc__ attribute.
Python Comments
Docstring comment
Python Comments
Output of Docstring __doc__
  • We have a lot of tools that auto-generate documentation from Docstring such as DoxygenPyDocpdocand the autodoc extension for Sphinx. 

1 comment:

  1. Is it advisable to add comment to every line of the code so that the administrator understands it?