2.3. Python Comments#

Python Comments are used to explain Python code. Comments can be used to make the code more readable. Comments can be used to prevent execution when testing code. Comments can be used to add a description to the code.

  1. Comments help to make code more readable, and can be used to explain what the code does.

  2. Comments can be used to prevent execution when testing code.

  3. Comments can be used to add a description to the code.

Comments start with a #, and Python will ignore them.

# This is a comment
print("Hello, World!")
Hello, World!

Comments can be placed at the end of a line, and Python will ignore the rest of the line:

print("Hello, World!") # This is a comment
Hello, World!

Comments does not have to be text to explain the code, it can also be used to prevent Python from executing code:

print("Hello, World!")
#print("Cheers, Mate!")
Hello, World!

Commeting ways

  1. Single line comment

  2. Multi line comment

2.3.1. Single Line Comment#

A single line comment is a comment that is written on a single line.

# Example 1: Single Line Comment

print("Hello, World!") # This is a comment
Hello, World!

2.3.2. Multi Line Comment#

A multi line comment is a comment that is written on multiple lines.

For multiple lines of comments you can use triple single quotes or triple double quotes.

# # Example 2: Multi Line Comment

"""
This is a comment
written in
more than just one line
"""
print("Hello, World!")
Hello, World!