Python – Comments

In Python, comments start with the hash character (#) that is not part of a string literal, and ends at the end of the physical line.

You cannot split a statement into multiple lines in Python by pressing Enter. Instead, use the backslash (\) to indicate that a statement is continued on the next line.

message = 'Hello, \
World'
print(message)

Output :

Hello, World

Triple quoted strings will automatically continue across the end of line statement.

message = '''Hello, 
World'''
print(message)

Output :

Hello, 
World

Python code example :

price = 100

# block comments

# increase price to 5%
price = price * 1.05


# inline comments
price = price * 1.02 # increase price to 2%

# multiline comments

"""
Python does not support multiline comments like C/C++ or Java. 
However there is nothing to stop you to use multi-line docstrings 
as multiline comments. This is also mentioned by Guido van Rossum, 
the creator of Python.
"""

# You can define a docstring with the help of triple-quotation mark.
# It must be the first statement in the object’s (module, function, class, and method) definition.

# one-line doc strings
def funcA():
    """This function sorts the list using quicksort algorithm """    
    print("Function A")
    
# multi-line doc strings
def increase_salary(sal,rating,percentage):
    """Increase salary based on rating and percentage
    rating 1 - 2 no increase
    rating 3 - 4 increase 5%
    rating 4 - 6 increase 10%
    """
    print("Multi-line Doc strings")

####### main starts here  ###############
    
print("Understanding Comments & Doc strings")

# Note: Doc strings can be accessed at run-time using <obj>.__doc__ attribute 
# where 'obj' is the name of function, module or class, etc.

print(funcA.__doc__)
# output : This function sorts the list using quicksort algorithm 

print(increase_salary.__doc__)

# Note: https://www.techbeamers.com/understand-python-comment-docstring/
# The Python interpreter won’t ignore the strings beginning with triple quotes
# as it does with the comments. They are executable statements. 
# And if they are not labeled, then they will be garbage collected as soon as the code executes.

Leave a comment