Python Comments

Comments can be used to explain Python code and to make the code more readable. Comments can be used to prevent execution when testing code.

Comments in Python

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

Single-Line Comments in Python

In Python, we use the hash symbol # to write a single-line comment.

Example:

# Print a message
print(“Hello Software Testers”)

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

Everything that comes after # is ignored by the Python Interpreter.

Example:

print(“Hello Python Programmers”) #This is a message

A comment does not have to be text that explains the code, it can also be used to prevent Python from executing code:

Example:

#print(“Hello Python World!”)
print(“Selenium Testers”)

Python Multi-Line Comments

Python does not really have a syntax for multi-line comments. To add a multiline comment you could insert a # for each line.

Example:

#Python supports the implicit declaration of Data Types
#User can check a variable Data type using the ‘type’ keyword
# Python is a case sensitive language
x=100
type(x) #int

We can use a multiline string for writing multi-line comments

Since Python will ignore string literals that are not assigned to a variable, you can add a multiline string (triple quotes) in your code, and place your comment inside it.

Example:

“””
This is a comment
written in
more than just one line
“””
print(“Hello Python World”)

Python docstrings

By convention, the triple quotes that appear right after the function, method or class definition are docstrings (documentation strings).

Docstrings are associated with objects and can be accessed using the __doc__ attribute.

Advantages of Using Comments:

Using comments in programs makes our code more understandable. It makes the program more readable which helps us remember why certain blocks of code were written.

Other than that, comments can also be used to ignore some code while testing other blocks of code. This offers a simple way to prevent the execution of some lines or write a quick pseudo-code for the program.

Python Step by Step Tutorial
Python Video Tutorial
Follow me on social media: