python tutorial - Python Comments - learn python - python programming
What is Python Comments?
- Comments in Python start with the hash character, #, and extend to the end of the physical line.
- A comment may appear at the start of a line or following whitespace or code, but not within a string literal.
- Commenting in Python is also quite different than other languages, but it is pretty easy to get used to.
- In Python, there are basically two ways to comment:
- Single line
- Multiple line.
Learn Python - Python tutorial - python comments - Python examples - Python programs
- Single line commenting is good for a short, quick comment (or for debugging), while the block comment is often used to describe something much more in detail or to block out an entire chunk of code.
1) Single lined comment:
- In case user wants to specify a single line comment, then comment must start with? #?
Example:
- # This is single line comment.
- In Python, we use the hash (#) symbol to start writing a comment.
- It extends up to the newline character.
- Comments are for programmers for better understanding of a program.
- Python Interpreter ignores comment.
Learn Python - Python tutorial - python single comments - Python examples - Python programs
2) Multi-line comments:
- If we have comments that extend multiple lines, one way of doing it is to use hash (#) in the beginning of each line.
For example:
Learn Python - Python tutorial - python multi comments - Python examples - Python programs
- Another way of doing this is to use triple quotes, either ''' or """.
- These triple quotes are generally used for multi-line strings.
- But they can be used as multi-line comment as well.
- Unless they are not docstrings, they do not generate any extra code.
Docstring in Python
- Docstring is short for documentation string.
- It is a string that occurs as the first statement in a module, function, class, or method definition.
- We must write what a function/class does in the docstring.
- Triple quotes are used while writing docstrings.
For example:
- Docstring is available to us as the attribute __doc__ of the function.