0% found this document useful (0 votes)
14 views8 pages

1 2comments

Uploaded by

Jad Matta
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views8 pages

1 2comments

Uploaded by

Jad Matta
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 8

Python Comments

Comments describe what is happening inside a program so that


a person looking at the source code does not have difficulty
figuring it out.

In this article, you’ll learn:

 How to add comments in your Python code


 The need of the comments
 What are the inline comments, block comments, and multi-
line comments
 The use of docstring comments.

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

What is Comment in Python?


The comments are descriptions that help programmers to
understand the functionality of the program. Thus, comments
are necessary while writing code in Python.

In Python, we use the hash (#) symbol to start writing a


comment. The comment begins with a hash sign (#) and
whitespace character and continues to the end of the line.
Many programmers commonly use Python for task automation,
data analysis, and data visualization. Also, Python has been
adopted by many non-programmers such as analysts and
scientists.

In a team, many programmers work together on a single


application. Therefore, if you are developing new code or
modifying the existing application’s code, it is essential
to describe the purpose behind your code using comments.

For example, if you have added new functions or classes in


the source code, describe them. It helps other colleagues
understand the purpose of your code and also helps in code
review.

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.

Writing comments is considered a good practice and required


for code quality.

If a comment is found while executing a script, the Python


interpreter completely ignores it and moves to the next
line.

Example:

x = 10
y = 20

# adding two numbers


z = x + y
print('Sum:', z)

# 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.

In Python, single-line comments are indicated by a hash


sign(#). The interpreter ignores anything written after the
# sign, and it is effective till the end of the line.

Primarily these comments are written over Python statements


to clarify what they are doing.

Example: Writing single-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

Add Sensible Comments


A comment must be short and straightforward, and sensible. A
comment must add value to your code.

You should add comments to give code overviews and provide


additional information that is not readily available in the
code itself.

Comments should contain only information that is relevant to


reading and understanding the program.

Let’s take the following example.

# Define list of student names

names = ['Jess', 'Emma', 'Kelly']

# iterates over name list and prints each name

for student in names:

print(student, end=' ')

As you can see, the code is self-explanatory, and adding


comments for such code is unnecessary. It would be best if
you avoided such scenarios.

Now, let’s take the second example where we have


demonstrated the correct way to write comments.
# Returns welcome message for a customer by customer name and location
# param name - Name of the customer
# param region - location
# return - Welcome message

def greet(name, region):


message = get_message(region)
return message + " " + name

# Returns welcome message by location


# param region - location
def get_message(region):
if (region == 'USA'):
return 'Hello'
elif (region == 'India'):
return 'Namaste'

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.

An inline comment is a comment on the same line as a


statement. Inline comments should be separated by at least
two spaces from the statement. They should start with
a # and a single space.

Inline comments are useful when you are using any formula or
any want to explain the code line in short.

If one or more lines contain the short comment, they should


all be indented to the same tab setting.

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.

Add a black line after the block comment to set it apart


from the rest of the code.

Example:

# Returns welcome message for a customer by customer name and location


# param name - Name of the customer
# param region - location
# return - Welcome message

def greet(name, region):


message = get_message(region)
return message + " " + name

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.

Conventions for writing good documentation strings are


mentioned in PEP 257

 The docstring comment should appear just after the


declaration.
 A docstring can be a single line or a multi-line
comment.
 Docstring should begin with a capital letter and end
with a period.
Example: docstring in function

def bonus(salary):
"""Calculate the bonus 10% of a salary ."""
return salary * 10 / 100

Write docstrings for all public modules, functions, classes,


and methods. Docstrings are not necessary for non-public
methods, but you should have a comment that describes what
the method does.

Commenting Out Code for Testing


If you are getting a runtime error or not getting an
expected output and cannot figure out which part of the code
is causing the problem, you can comment out the specific
block or a line to quickly figure out the problem.

Example:

def greet(name, region):


# below code is comment for testing
# message = get_message(region)
message= 'Hello'
return message + " " + name

def get_message(region):
if (region == 'USA'):
return 'Hello'
elif (region == 'India'):
return 'Namaste'

print(greet('Jessa', 'USA'))

Run

Using String Literals for Multi-


line Comments
As we discussed, there is no unique way to write multi-line
comments. We can use multi-line strings (triple quotes) to
write multi-line comments. The quotation character can
either be ‘ or “.

Python interpreter ignores the string literals that are not


assigned to a variable.

Example

'''

I am a
multiline comment!

'''
print("Welcome to PYnative..")

In the above example, the multi-line string isn’t assigned


to any variable, so the interpreter ignores it. Even it is
not technically a multi-line comment.

Summary
The comments are descriptions that help programmers to
understand the functionality of the program. Thus, comments
are necessary while writing code in Python.

 Use the hash (#) symbol to start writing a comment in


Python
 Comments should contain only information that is
relevant to reading and understanding the program.
 Python dosen’t support multi-line comments. we need to
use a hash sign at the beginning of each comment line to
make it a multi-line comment
 Keep comments indentation uniform and match for best
readability.
 Add Docstring to functions and classes

You might also like