Comments In Python


The comments in a programming language are used to explain something in the source code. For example, it can be used to explain what a line of code or block of code is doing.

It enhances the readability of code that means if a source code is given to someone else for modification, he can easily understand things if explained with the help of comments. Each programming language uses a different syntax for comments.

Why comments are used?

A comment in a source code can be used to –

  • Explain what a line or block of code if doing
  • Enhance the readability of source code
  • Comments are ignored by compilers or interpreters. So it can be used to prevent the execution while testing the code
  • Comments are processed in various ways to generate documentation by using a document generator

Comments in Python

For writing comments in Python code, you need to use # at the starting of a line. Python interpreter ignores the lines that are starting with # symbol.

Single line comment

Put a # symbol before writing your comment.

For example –

#This is a single line comment

print ("Hello World!")

Multi-line comment

Python doesn’t have a different way of writing multiline comments, you need to use # at the starting of each line.

#This is a multi-line
#comment in Python

print("Hello World!")

Best practices while using comments in Python

  • Write short and concise comments that explain the code
  • Write clean and self-explanatory code so you need not explain so many things of source code using comments
  • Try to identify and remove all the comments that are redundant

You have learned how to use comments in the Python programming language. Now you can put your thoughts in the comments below.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.