Python Comments
Comments are essential when writing a program because they describe what happens inside a program.
In Python, to start writing a comment you use the hash symbol # which extends to the newline character.
print('Hello world')
print('Hello!') # print an other stringHello world
Hello!Advantages of Using Comments
The use of comments in programs makes your code more understandable. It makes the program more readable and helps you remember why certain blocks of code were written.
Comments can be used also to ignore some code while testing other blocks of code. This offers a simple way to prevent the execution of some lines.
Single-Line Comments in Python
In Python, the hash symbol # is used to write a single-line comment.
In this way the line is ignored by the Python interpreter.
print('Hello world')Multi-Line Comments in Python
Python does not provide a separate way to write multi-line comments. However, you can get around this problem by using # at the beginning of each multi-line comment line.
String Literals for Multi-line Comments
The Python interpreter ignores string literals that are not assigned to a variable, so you can write a single-line comment as:
'this is an unassigned string as a comment 'Similarly, you can use multiline strings (triple quotes) to write multiline comments.
The quotation character can either be ' or ".
For example:
'''
I am a
multiline comment!
'''
print("Hello World")Python docstrings
By convention, the triple quotes that appear right after the function, method or class definition are docstrings (documentation strings).
To learn more, visit Python docstrings.