Python Logo

Comment


Python comments are used to explain the code or to make it more readable. Comments are ignored by the Python interpreter, so they do not affect the execution of the program.

There are two types of Python comments: single-line comments and multi-line comments.

Single-line comments

Single-line comments start with the hash symbol (#) and extend to the end of the line. For example:

 

Python

# This is a single-line comment.
print("Hello, World!")
 

Multi-line comments

Multi-line comments start with three single quotes or three double quotes (``` or """), and end with the same three characters. For example:

 

Python

"""
This is a multi-line comment.
"""

print("Hello, World!")
 

Here are some examples of how to use Python comments:

  • To explain the purpose of a block of code:

 

Python

# This function calculates the area of a rectangle.
def calculate_rectangle_area(length, width):
  return length * width

# This code prints the area of a rectangle to the console.
print(calculate_rectangle_area(5, 10))
 

  • To explain a complex algorithm:

 

Python

# This code sorts a list of numbers in ascending order using the quicksort algorithm.
def quicksort(list1):
  if len(list1) <= 1:
    return list1

  pivot = list1[0]
  less = [x for x in list1[1:] if x < pivot]
  greater = [x for x in list1[1:] if x >= pivot]

  return quicksort(less) + [pivot] + quicksort(greater)

# This code prints the sorted list to the console.
print(quicksort([5, 3, 2, 1, 4]))
 

  • To disable code that is currently not in use:

 

Python

# This code is used to connect to a database, but it is not currently in use.
# import mysql.connector

# This code prints a message to the console.
print("Database connection is disabled.")
 

  • To remind yourself of something:

 

Python

# TODO: Implement the user login feature.


Comments are a valuable tool for making your code more readable and understandable. It is a good practice to add comments to your code whenever necessary.