Inline Comments
We'll cover the following
Inline comments
Inline comments are used on the same line as code and depict where to stop parsing the code. This is because the content between after the #
sign and before the line ends is ignored and not considered a part of the code. They’re mainly used to add short phrases in front of variables or functionalities.
For example, the following code uses various physics constants, and the comments in front of them explain what these constants stand for in order to improve readability.
G = 6.67430e-11 # Gravitational constantm1 = 5.972e24 # Mass of the Earthm2 = 7.342e22 # Mass of the Moonr = 3.844e8 # Distance between the Earth and the Moon# Newton's law - gravitational formulagravitational_force = G * (m1 * m2) / r**2print(f"The gravitational force between the Earth and the Moon is = {gravitational_force} N")
It’s not necessary to explain each line, and comments should only be used when necessary for good documentation. If appropriate coding practices (i.e., proper variable names) are used, comments become less necessary. That said, good practices don’t eliminate the need for coding entirely.
Note: It is a good practice to start an inline comment at least with a gap of two spaces from the code.