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.
 python comments

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.
 python comment

1) Single lined comment:

  • In case user wants to specify a single line comment, then comment must start with? #?

Example:

  1. # 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.
 python single comments

Learn Python - Python tutorial - python single comments - Python examples - Python programs

#This is a comment
#print out Hello
print('Hello')
click below button to copy the code. By Python tutorial team

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:

#This is a long comment
#and it extends
#to multiple lines
click below button to copy the code. By Python tutorial team
python multi comments

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.
"""This is also a
perfect example of
multi-line comments"""
click below button to copy the code. By Python tutorial team

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:

def double(num):
    """Function to double the value"""
    return 2*num
click below button to copy the code. By Python tutorial team
  • Docstring is available to us as the attribute __doc__ of the function.
>>> print(double.__doc__)
Function to double the value
click below button to copy the code. By Python tutorial team

Related Searches to Python Comments