Site icon Meccanismo Complesso

Python Lessons – 3.5 Comments and Docstrings

Python Lessons - 3.5 Comments and Docstrings
Python Lessons - 3.5 Comments and Docstrings

Comments

When writing a programming code, it is always important to add annotations to make more understandable what is written, not only for others, but also for themselves.

In the Python language, the comments are identified by inserting a # (sharp) sign at the beginning of the line. All the text that will be written following this character will be a comment and will not be considered at run time.

So the comments increase the readability of the code and are a prerogative for the drafting of a good code.

# Questo è un commento
i = 1 # Ma anche questo è un commento

Often comments are very useful even in the phase of dedugation, putting a few lines of code in the form of comments, eliminating them from execution but only temporarily, so as not to forget them and to reactivate them in a moment by deleting the # character.

Docstrings

There is another method that allows you to add a few lines of text to the code and avoid it being considered during the execution of the program. This method is based on the docstrings, characterized by lines of text enclosed between “”” and “”” (a triplet of double quotes).

Actually the docstrings were not born to write comments in the code, but to give explanations. They allow you to add more lines of text to the code, and they are usually inserted at the beginning of a program or at the beginning of a function to explain how it works.

def foo():
"""
Questa funzione serve solo per dare
una spiegazione su come si usano le docstrings
"""

Attention, unlike comments, docstrings, even if not executed, are actually stored at runtime and can be called if one wishes, with the __doc__ attribute

print(foo.__doc__)
>>>

This function only serves to give an explanation of how the docstrings are used

⇐ Go to Python Lesson 3.4 – Values returned by the functions

Go to Python Lesson 3.6 – Functions as objects ⇒

Exit mobile version