The Wayback Machine - https://web.archive.org/web/20240914143553/https://www.geeksforgeeks.org/python-comments/
Open In App

Python Comments: Importance, Types and Correct Way to Use

Last Updated : 08 Jan, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Comments in Python are the lines in the code that are ignored by the interpreter during the execution of the program.




# I am single line comment
  
  
""" Multi-line comment used
print("Python Comments") """


Comments enhance the readability of the code and help the programmers to understand the code very carefully. It also helps in collaborating with other developers as adding comments makes it easier to explain the code.

Types of Comments in Python

There are three types of comments in Python:

  • Single line Comments
  • Multiline Comments
  • String Literals
  • Docstring Comments

Comments in Python

In the example, it can be seen that Python Comments are ignored by the interpreter during the execution of the program.

Python3




# sample comment
name = "geeksforgeeks"
print(name)


Output: 

geeksforgeeks

Why are Comments Used in Python?

Comments have been an integral part of programming languages, and every language have different ways of using comments.

Just like any other language, comments in Python serve following purpose:

  1. Enhance code readability
  2. Explaining code to other
  3. Understanding code if studied after some time
  4. Documenting the steps and needs for a function
  5. Sharing code with fellow developers
  6. Collaborating with multiple people.

Types of Comments in Python

Let’s discover the different types of comments, how to use them and when to use them?

1. Single-Line Comments

  • Python single-line comment starts with the hashtag symbol (#) with no white spaces and lasts till the end of the line.
  • If the comment exceeds one line then put a hashtag on the next line and continue the Python Comment.
  • Python’s single-line comments are proved useful for supplying short explanations for variables, function declarations, and expressions. See the following code snippet demonstrating single line comment:

Example: 

Python3




# Print “GeeksforGeeks !” to console
print("GeeksforGeeks")


Output

GeeksforGeeks




2. Multi-Line Comments

Python does not provide the option for multiline comments. However, there are different ways through which we can write multiline comments.

a) Multiline comments using multiple hashtags (#)

We can multiple hashtags (#) to write multiline comments in Python. Each and every line will be considered as a single-line comment.

Python3




# Python program to demonstrate
# multiline comments
print("Multiline comments")


Output

Multiline comments




Also Check: Interesting Fact about Python Multi-line Comments

3. String Literals

Python ignores the string literals that are not assigned to a variable so we can use these string literals as Python Comments

a) Single-line comments using string literals

On executing the above code we can see that there will not be any output so we use the strings with triple quotes(“””) as multiline comments.

Python3




'This will be ignored by Python'


b) Multiline comments using string literals

Python3




""" Python program to demonstrate
 multiline comments"""
print("Multiline comments")


Output

Multiline comments




4. Docstring

  • Python docstring is the string literals with triple quotes that are appeared right after the function.
  • It is used to associate documentation that has been written with Python modules, functions, classes, and methods.
  • It is added right below the functions, modules, or classes to describe what they do. In Python, the docstring is then made available via the __doc__ attribute.

Example:

Python3




def multiply(a, b):
    """Multiplies the value of a and b"""
    return a*b
  
  
# Print the docstring of multiply function
print(multiply.__doc__)


Output: 

Multiplies the value of a and b

Advantages of Comments in Python

Comments are generally used for the following purposes: 

  • Code Readability
  • Explanation of the code or Metadata of the project
  • Prevent execution of code
  • To include resources

Right Way to Write Comments

Comments serve the main purpose to explain your code. Developers use healthy comment writing practice for better understanding of the code.

Some of the tips you can follow, to make your comments effective are:

  1. Comments should be short and precise.
  2. Use comments only when necessary, don’t clutter your code with comments.
  3. Comment should have some meaning.
  4. Avoid writing generic or basic comments.
  5. Write comments that are self explanatory.

We have discussed all about Python comments, how to write Python comments, types of comment,what are it’s advantages and the right way to write comments.

Also Read: How to write Comments in Python3?



Similar Reads

Python | TextBlob.correct() method
With the help of TextBlob.correct() method, we can get the corrected words if any sentence have spelling mistakes by using TextBlob.correct() method. Syntax : TextBlob.correct() Return : Return the correct sentence without spelling mistakes. Example #1 : In this example, we can say that by using TextBlob.correct() method, we are able to get the cor
1 min read
Interesting Fact about Python Multi-line Comments
Multi-line comments(comments block) are used for description of large text of code or comment out chunks of code at the time of debugging application.Does Python Support Multi-line Comments(like c/c++...)? Actually in many online tutorial and website you will find that multiline_comments are available in python(""" or '''). but let's first look at
3 min read
How do we create multiline comments in Python?
Comments are pieces of information present in the middle of code that allows a developer to explain his work to other developers. They make the code more readable and hence easier to debug. Inline Comment An inline comment is a single line comment and is on the same line as a statement. They are created by putting a '#' symbol before the text. Synt
3 min read
How to Extract YouTube Comments Using Youtube API - Python
Prerequisite: YouTube API Google provides a large set of API’s for the developer to choose from. Each and every service provided by Google has an associated API. Being one of them, YouTube Data API is very simple to use provides features like – Search for videosHandle videos like retrieve information about a video, insert a video, delete a video et
2 min read
Multiline comments in Python
In this article, we will delve into the concept of multiline comments in Python, providing a comprehensive definition along with illustrative examples in the Python programming language on How to Comment Multiple lines in Python. What is a Multiline Comment in Python? Multiline comments in Python refer to a block of text or statements that are used
4 min read
Integrating Facebook Like, Comments and Share Plugin in Flask Project
Flask is a Framework of Python that allows us to build up web-applications. It was developed by Armin Ronacher. Flask’s framework is more explicit than Django’s framework and is also easier to learn because it has less base code to implement a simple web-Application. This article revolves around how to integrate Facebook comments plugin in flask ap
2 min read
Check if the Depth of Parentheses is correct in the given String
Given a string S consisting of opening parentheses, closing parentheses and integers, the task is to print Yes if, in this string, the integers correctly indicates its depth. Depth refers to the number of nested sets of parentheses surrounding that integer. Print No otherwise.Examples: Input: S = "((2)((3)))" Output: Yes Explanation: No of Opening
7 min read
How to write Comments in Python3?
Comments are text notes added to the program to provide explanatory information about the source code. They are used in a programming language to document the program and remind programmers of what tricky things they just did with the code and also help the later generation for understanding and maintenance of code. The compiler considers these as
4 min read
Comments in Ruby
Statements that are not executed by the compiler and interpreter are called Comments. During coding proper use of comments makes maintenance easier and finding bugs easily.In Ruby, there are two types of comments: Single – line comments.Multi – line comments. Here, we are going to explain both types of comment with their syntax and example: Ruby Si
2 min read
Integrating Facebook Comments Plugin in Django Project
Django is a Python-based web framework that allows you to quickly create efficient web applications. It is also called batteries included framework because Django provides built-in features for everything including Django Admin Interface, default database – SQLlite3, etc. In this article, we will learn to integrate the Facebook comment plugin in Dj
2 min read
Django project to create a Comments System
Commenting on a post is the most common feature a post have and implementing in Django is way more easy than in other frameworks. To implement this feature there are some number of steps which are to be followed but first lets start by creating a new project. How to create Comment Feature in Django?Open command prompt and run the following commands
6 min read
Converting Jinja Comments into Documentation
Developers often face the challenge of creating comprehensive documentation for their code. However, by leveraging Jinja, a powerful template engine for Python, it becomes possible to automatically generate documentation from code comments. This article will explore the process of using Jinja to extract information from code comments and create str
5 min read
What is a clean and Pythonic way to have multiple constructors in Python?
Python does not support explicit multiple constructors, yet there are some ways to achieve multiple constructors. We use Python's inbuilt __init__ method to define the constructor of a class. It tells what will the constructor do if the class object is created. If multiple __init__ methods are written for the same class, then the latest one overwri
7 min read
Most Efficient Way To Find The Intersection Of A Line And A Circle in Python
To make an efficient algorithm to find the intersection of a line and a circle, we need to understand what lines and circles are and how we can mathematically represent and calculate them in Python. Prerequisites LineCirclesQuadratics EquationsSolving a Quadratic EquationQuadratic Formula/Sridharacharya FormulaMathematical ApproachTo find the inter
8 min read
Python List Comprehension | Three way partitioning of an array around a given range
Given an array and a range [lowVal, highVal], partition the array around the range such that array is divided in three parts. 1) All elements smaller than lowVal come first. 2) All elements in range lowVal to highVal come next. 3) All elements greater than highVal appear in the end. The individual elements of three sets can appear in any order. Exa
3 min read
Change your way to put logic in your code - Python
Aren't you bored coding in the same traditional logic over these years. It's time to bring some differences. Well, be it any programming language. When we are asked to do some sort of basic programming exercises like sorting, searching, prime number checking, etc. we are all driven towards the same boat, which is the same coding logic. Now, we are
5 min read
Different way to create a thread in Python
A thread is an entity within a process that can be scheduled for execution. Also, it is the smallest unit of processing that can be performed in an Operating System. There are various ways to create a thread: 1) Create a Thread without using an Explicit function: By importing the module and creating the Thread class object separately we can easily
4 min read
Cropping an Image in a circular way using Python
In this article, we will learn to crop an image circularly using a pillow library. Cropping an image circularly means selecting a circular region inside an image and removing everything outside the circle. Approach: If you have an L mode image, the image becomes grayscale. So we create a new image with mode "L".An image is created with a white circ
2 min read
How to Perform a Two-Way ANOVA in Python
Two-Way ANOVA: Two-Way ANOVA in statistics stands for Analysis of Variance and it is used to check whether there is a statistically significant difference between the mean value of three or more that has been divided into two factors. In simple words, ANOVA is a test conducted in statistics and it is used to interpret the difference between the mea
3 min read
How to Perform a One-Way ANOVA in Python
One-Way ANOVA in Python: One-way ANOVA (also known as "analysis of variance") is a test that is used to find out whether there exists a statistically significant difference between the mean values of more than one group. Hypothesis involved: A one-way ANOVA has the below given null and alternative hypotheses: H0 (null hypothesis): μ1 = μ2 = μ3 = …
2 min read
Bidirectional Hash table or Two way dictionary in Python
We know about Python dictionaries in a data structure in Python which holds data in the form of key: value pairs. In this article, we will discuss the Bidirectional Hash table or Two-way dictionary in Python. We can say a two-way dictionary can be represented as key ⇐⇒ value. One example of two-way dictionaries is: Example: dict={ 1 : 'Apple' , 2 :
3 min read
Best way to learn python
Python is a versatile and beginner-friendly programming language that has become immensely popular for its readability and wide range of applications. Whether you're aiming to start a career in programming or just want to expand your skill set, learning Python is a valuable investment of your time. This article guide to help you start your journey
11 min read
Python | Using 2D arrays/lists the right way
Python provides powerful data structures called lists, which can store and manipulate collections of elements. Also provides many ways to create 2-dimensional lists/arrays. However one must know the differences between these ways because they can create complications in code that can be very difficult to trace out. In this article, we will explore
9 min read
Best Way To Start Learning Python - A Complete Roadmap
Python...The world's fastest-growing and most popular programming language not just amongst software engineers but also among mathematicians, data analysts, scientists, accountants, network engineers, and even kids! because it's a very beginner-friendly programming language. People from different disciplines use Python for a variety of different ta
10 min read
Fastest way to Convert Integers to Strings in Pandas DataFrame
Pandas - An open-source library which is used by any programmer. It is a useful library that is used for analyzing the data and for manipulating the data. It is fast, flexible, and understandable, handles the missing data easily. Not only it provides but also enhances the performance of data manipulation and analysis tools with the powerful data st
2 min read
Plotting In A Non-Blocking Way With Matplotlib
When we plot a graph with Matplotlib, by default the execution of the code is stopped/blocked when it is viewed/drawn until the view window is closed. However, in certain cases, one may want to remove this blocking behavior and see the graph as soon as it is plotted or updated without blocking the program execution. This article addresses this issu
5 min read
Argparse: Way to include default values in '--help'?
Argparse in Python allows you to create user-friendly command-line interfaces. By including default values in the --help output, you can make your script's behavior more transparent. There are several ways to achieve this, including using argparse.ArgumentDefaultsHelpFormatter and custom help formatters. Include default values in '--help'Below are
2 min read
What is the Proper Way to Call a Parent's Class Method Inside a Class Method?
In object-oriented programming, calling a parent class method inside a class method is a common practice, especially when you want to extend or modify the functionality of an inherited method. This process is known as method overriding. Here's how to properly call a parent class method inside a class method in Python. Basic Syntax Using super()The
3 min read
What is the fastest way to drop consecutive duplicates a List[int] column?
Handling data efficiently is a critical task in many programming and data analysis scenarios. One common problem is dealing with consecutive duplicates in lists, especially when working with columns of data in formats like CSV files or databases. This article explores the fastest ways to drop consecutive duplicates from a List[int] column, ensuring
3 min read
What is a Pythonic Way for Dependency Injection?
Design pattern Dependency Injection (DI) achieves Inversion of Control (IoC) between classes and their dependencies. DI increases testability and modularity by externalizing the building and control of dependencies. This post will investigate DI from a Pythonic standpoint with an eye toward best practices and pragmatic solutions. Understanding Depe
4 min read
Practice Tags :