Sometimes when you are writing Python code, you feel like you want to explain the code that you are writing, by writing comments on it. In order to use it as a reference for anybody who will read your code in the future including yourself, because, believe me, when you read the code that you have written yourself in the future, you are not going to remember or understand anything from it.
- Comments can be used to explain Python code.
- Comments can be used to make the code more readable.
- Comments can be used to prevent execution when testing code.
But, how can you do that?
Comments start with a
#, and the Python interpreter will ignore them.
Comments can be placed at the end of a line, and Python will ignore the rest of the line
A comment does not have to be text that explains the code, it can also be used to prevent Python from executing code
Python does not really have a syntax for multi-line comments.
To add a multiline comment you could insert a
# for each line.
Or, not quite as intended, you can use a multiline string, Since Python will ignore string literals that are not assigned to a variable, you can add a multiline string (triple quotes) in your code, and place your comment inside it.
As long as the string is not assigned to a variable, Python will read the code, but then ignore it, and you have made a multiline comment.
Python comments can help you write more maintainable and readable code and save you, your teammates, and future developers on your project a lot of time and effort.