PYnative

Python Programming

  • Learn Python
  • Exercises
  • Quizzes
  • Code Editor
  • Tricks
Home » Python » Python Comments

Python Comments

Updated on: August 22, 2022 | 4 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 for 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

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...')

Output:

Welcome to PYnative...

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...')

Output

Welcome to PYnative...

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'))

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'))

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

Filed Under: Python, Python Basics

Did you find this page helpful? Let others know about it. Sharing helps me continue to create free Python resources.

TweetF  sharein  shareP  Pin

About Vishal

Founder of PYnative.com I am a Python developer and I love to write articles to help developers. Follow me on Twitter. All the best for your future Python endeavors!

Related Tutorial Topics:

Python Python Basics

Python Exercises and Quizzes

Free coding exercises and quizzes cover Python basics, data structure, data analytics, and more.

  • 15+ Topic-specific Exercises and Quizzes
  • Each Exercise contains 10 questions
  • Each Quiz contains 12-15 MCQ
Exercises
Quizzes

Posted In

Python Python Basics
TweetF  sharein  shareP  Pin

  Python Tutorials

  • Get Started with Python
  • Python Statements
  • Python Comments
  • Python Keywords
  • Python Variables
  • Python Operators
  • Python Data Types
  • Python Casting
  • Python Control Flow statements
  • Python For Loop
  • Python While Loop
  • Python Break and Continue
  • Python Nested Loops
  • Python Input and Output
  • Python range function
  • Check user input is String or Number
  • Accept List as a input from user
  • Python Numbers
  • Python Lists
  • Python Tuples
  • Python Sets
  • Python Dictionaries
  • Python Functions
  • Python Modules
  • Python isinstance()
  • Python Object-Oriented Programming
  • Python Exceptions
  • Python Exercise for Beginners
  • Python Quiz for Beginners

All Python Topics

Python Basics Python Exercises Python Quizzes Python File Handling Python OOP Python Date and Time Python Random Python Regex Python Pandas Python Databases Python MySQL Python PostgreSQL Python SQLite Python JSON

About PYnative

PYnative.com is for Python lovers. Here, You can get Tutorials, Exercises, and Quizzes to practice and improve your Python skills.

Explore Python

  • Learn Python
  • Python Basics
  • Python Databases
  • Python Exercises
  • Python Quizzes
  • Online Python Code Editor
  • Python Tricks

Follow Us

To get New Python Tutorials, Exercises, and Quizzes

  • Twitter
  • Facebook
  • Sitemap

Legal Stuff

  • About Us
  • Contact Us

We use cookies to improve your experience. While using PYnative, you agree to have read and accepted our Terms Of Use, Cookie Policy, and Privacy Policy.

Copyright © 2018–2023 pynative.com