Comments are notes written inside a Python program to explain the code. They help programmers understand what the code does and make programs easier to read and maintain.
A comment is explanatory text written inside source code. Comments are intended for programmers rather than the Python interpreter.
The comment is ignored during execution, while the print() statement is executed.
Comments improve the readability and maintainability of a program.
Comments can be used to:
A single-line comment begins with the # symbol.
Everything after # on that line is treated as a comment, unless the symbol appears inside a string.
A comment can be written before a statement to explain what the statement does.
A comment can also be written after a Python statement on the same line.
Inline comments should be used when they add useful information that is not already obvious from the code.
Python does not have a special multi-line comment operator. To write a comment across several lines, place # at the beginning of each line.
You may see triple-quoted strings used to write text across multiple lines.
For normal comments, using # on each line is clearer and more accurate.
Triple-quoted strings have an important use in Python called docstrings. A docstring documents a module, function, class, or method.
Unlike ordinary comments, docstrings can be accessed by Python tools and programs.
During testing, you can place # before a line to prevent that line from executing.
The second print() statement does not execute because it has been commented out.
Comments can explain variables when their purpose is not immediately clear.
Comments can be used to explain the purpose of conditions and business rules.
Comments can explain why a loop is being used.
A good comment explains information that is useful but not obvious from the code.
This comment simply repeats what the code already says.
This comment explains why the value exists.
Let's create a simple program containing several comments.
Write Python programs for the following tasks and add suitable comments.
Which symbol is used to start a single-line comment in Python?