1 2comments
1 2comments
Table of contents
What is Comment in Python?
Single-line Comment
Multi-Line Comments
Add Sensible Comments
Inline Comments
Block Comments
Docstring Comments
Commenting Out Code for Testing
Using String Literals for Multi-line Comments
Summary
Apart from this, In the future, it helps to find and fix the
errors, improve the code later on, and reuse it in many
different applications.
Example:
x = 10
y = 20
# Output 30
Run
As you can see in the above program, we have added the
comment ‘adding two numbers’.
Single-line Comment
Python has two types of comments single-line and multi-line
comments.
# welcome message
print('Welcome to PYnative...')
Run
Output:
Welcome to PYnative...
Run
Note: By considering the readability of a code, limit the
comment line to a maximum of 79 characters as per the PEP 8
style guide.
Multi-Line Comments
In Python, there is no separate way to write a multi-line
comment. Instead, we need to use a hash sign at the
beginning of each comment line to make it a multi-line
comment
Example
# This is a
# multiline
# comment
print('Welcome to PYnative...')
Run
Output
Welcome to PYnative...
Run
print(greet('Jessa', 'USA'))
Run
Inline Comments
We can add concise comments on the same line as the code
they describe but should be shifted enough to separate them
from the statements for better readability. It is also
called a trailing comment.
Inline comments are useful when you are using any formula or
any want to explain the code line in short.
Example:
def calculate_bonus(salary):
salary = salary * 7.5 # yearly bonus percentage 7.5
Block Comments
Block comments are used to provide descriptions of
files, classes, and functions. We should add block comments
at the beginning of each file and before each method.
Example:
Docstring Comments
Docstring comments describe
Python classes, functions, constructors, methods. The
docstring comment should appear just after the declaration.
Although not mandatory, this is highly recommended.
def bonus(salary):
"""Calculate the bonus 10% of a salary ."""
return salary * 10 / 100
Example:
def get_message(region):
if (region == 'USA'):
return 'Hello'
elif (region == 'India'):
return 'Namaste'
print(greet('Jessa', 'USA'))
Run
Example
'''
I am a
multiline comment!
'''
print("Welcome to PYnative..")
Summary
The comments are descriptions that help programmers to
understand the functionality of the program. Thus, comments
are necessary while writing code in Python.