Comments in python example

Python Comments – Multiline Comments, Best Practices

Comments are an integral part of any program. Every programming language provides a way to add comments. Python commenting system is very easy. In this guide, we will learn about comments in Python. They provide useful information about the code to the developers.

How to Write Comments in Python?

  • Python comments start with the # character and extend to the end of the line.
  • We can start a comment from the start of the line, after some whitespaces or code.
  • If the hash character is present in a string literal, it’s part of the string.

Python Comments Examples

We can add comments for variables, functions, and classes. They are used to provide the intended use of the part of the code. Let’s look at some examples of comments in Python.

1. Comment for Variables

name = "Pankaj" # employee name id = 100 # employee id data = "#123" # this is comment, data contains # and that is not part of the comment.

2. Comments for Functions

# This function adds the two numbers def add(x, y): return x+y

Python Comments

3. Comments for Class

# This class provides utility functions to work with Strings class StringUtils: def reverse(s): return ''.join(reversed(s))

Python Comment Block or Multiline Comment

Sometimes it’s not feasible to have the comment in a single line. In this case, we can create a comment block or split the comment into multiple lines. We have to prefix every line with the hash (#) to write a multiline comment.

# This class provides utility functions to work with Strings # 1. reverse(s): returns the reverse of the input string # 2. print(s): prints the string representation of the input object class StringUtils: def reverse(s): return ''.join(reversed(s)) def print(s): print(s)

Python Multiline Comment

Using Python Docstring as Multiline Comment

Python documentation strings (Docstring) are used to provide documentation for functions, classes, and modules. They are defined between a pair of triple double-quotes (“””). They must be defined just below the function or class declaration.

Читайте также:  Unit testing with python

Let’s have a quick look at some examples of Python docstrings.

def foo(): """The foo() function needs to be implemented. Currently, this function does nothing.""" pass class Data: """ This class is used to hold Data objects information."""

We can access the docstring of an entity using __doc__ attribute.

print(foo.__doc__) print(Data.__doc__)

Python Docstrings

Is it a good idea to use Docstring to specify long multiline comments?

Python docstrings’ purpose is to provide documentation. Sometimes you will notice that it’s misused to provide long comments. However, it’s not the recommended approach. If you want the comment to spread into multiple lines, just prefix every line with the hash character.

Python Multiline String as Multiline Comments

We can also use multiline strings as multiline comments. According to this Guido’s tweet, they generate no code.

''' This function read employees data from the database emp_id: employee id, should be int returns employee object. ''' def read_emp_from_db(emp_id): i = int(emp_id) '''code to read emp data using the employee unique id number''' pass

However, it can lead to issues with indentation. It’s also confusing as to why a string is present in the code without any use. So, it’s better to stick to the regular multiline comments using hash characters.

Python Commenting Best Practices

  • Always provide meaningful comments to specify the use of the entity.
  • It’s better to break the long comment into multiple lines.
  • Don’t be rude in the comments.
  • Keep the comments to the point. Nobody wants to read a novel in the code comments.
  • Avoid useless comments that don’t provide any useful information. Below are some examples of useless comments.
# count variable count = 10 # foo() function def foo(): pass
  • Sometimes comments are unnecessary. Having the proper name of the entity itself is good enough. Let’s look at an example of this scenario.
# This function add two numbers def foo(x, y): return x + y # Better to have function defined as below. There is no use of comments. def add_two_numbers(x, y): return x + y
  • It’s always a good idea to have a commenting system in place. When working with many team members and multiple projects in an organization, using a commenting policy is recommended. For example, you can define a commenting policy like this:
# - # Data Object - stores the Data fetched from the database data_obj = Data() # # # # # This function adds all the elements in the sequence or iterable # numbers: sequence or iterable, all the elements must be numbers # Returns the sum of all the numbers in the sequence or iterable # Throws ArithmeticError if any of the element is not a number def add_numbers(numbers): sum_numbers = 0 for num in numbers: sum_numbers += num return sum_numbers

Python Comment Shortcut to Comment Out a Block

If you are working with Python IDE or Jupyter Notebook, you can use a shortcut to comment out a block of the code.

  • macOS Comment Shortcut – Select the lines you want to comment and press Command+/ and it will automatically add # at the start of each line to turn them into a comment block. If it’s a blank line, it will add # at the start of the line and you can write the comment.
  • Windows and Linux Comment Shortcut – Use Ctrl+/ as the shortcut to turn a code block into a comment.

Summary

  • Python commenting system is simple and always starts with #.
  • Python docstring is used for documentation. You should not misuse it for multiline comments.
  • Start every line with the hash character for multiline comments.
  • Follow the best practices for adding comments to the program.
  • Having a commenting policy in place is always a good idea when working with many team members.

What’s Next?

We referenced a lot of topics in this tutorial, you should read the following tutorials to get a further understanding of them.

References:

Источник

Python Comments

Summary: in this tutorial, you’ll learn how to add comments to your code. And you’ll learn various kinds of Python comments including block comments, inline comments, and documentation string.

Introduction to Python comments

Sometimes, you want to document the code that you write. For example, you may want to note why a piece of code works. To do it, you use the comments.

Typically, you use comments to explain formulas, algorithms, and complex business logic.

When executing a program, the Python interpreter ignores the comments and only interprets the code.

Python provides three kinds of comments including block comment, inline comment, and documentation string.

Python block comments

A block comment explains the code that follows it. Typically, you indent a block comment at the same level as the code block.

To create a block comment, you start with a single hash sign ( # ) followed by a single space and a text string. For example:

# increase price by 5% price = price * 1.05Code language: Python (python)

Python inline comments

When you place a comment on the same line as a statement, you’ll have an inline comment.

Similar to a block comment, an inline comment begins with a single hash sign ( # ) and is followed by a space and a text string.

The following example illustrates an inline comment:

salary = salary * 1.02 # increase salary by 2%Code language: Python (python)

Python docstrings

A documentation string is a string literal that you put as the first lines in a code block, for example, a function.

Unlike a regular comment, a documentation string can be accessed at run-time using obj.__doc__ attribute where obj is the name of the function.

Typically, you use a documentation string to automatically generate the code documentation.

Documentation strings is called docstrings.

Technically speaking, docstrings are not the comments. They create anonymous variables that reference the strings. Also, they’re not ignored by the Python interpreter.

Python provides two kinds of docstrings: one-line docstrings and multi-line docstrings.

1) One-line docstrings

As its name implies, a one-line docstring fits one line. A one-line docstring begins with triple quotes ( «»» ) and also ends with triple quotes ( «»» ). Also, there won’t be any blank line either before or after the one-line docstring.

The following example illustrates a one-line docstring in the quicksort() function:

def quicksort(): """ sort the list using quicksort algorithm """ . Code language: Python (python)

2) Multi-line docstrings

Unlike a one-line docstring, a multi-line docstring can span multiple lines. A multi-line docstring also starts with triple quotes ( «»» ) and ends with triple quotes ( «»» ).

The following example shows you how to use multi-line docstrings:

def increase(salary, percentage, rating): """ increase salary base on rating and percentage rating 1 - 2 no increase rating 3 - 4 increase 5% rating 4 - 6 increase 10% """Code language: Python (python)

Python multiline comments

Python doesn’t support multiline comments.

However, you can use multi-line docstrings as multiline comments. Guido van Rossum, the creator of Python, also recommended this.

It’s a good practice to keep your comment clear, concise, and explanatory. The ultimate goal is to save time and energy for you and other developers who will work on the code later.

Summary

  • Use comments to document your code when necessary.
  • A block comment and inline comment starts with a hash sign ( # ).
  • Use docstrings for functions, modules, and classes.

Источник

Оцените статью