To explain the functionality of Python code, comments must be used. It can be used to make the code more readable. It can be used to prevent execution when testing code.
A hash sign (#) that is not inside a string literal begins a comment. All characters after the # and up to the physical line end are part of the comment, and the Python interpreter ignores them.
# First comment print("Hello, World!") # second comment
This will produce following result:
Hello, World!
Single Line Comment
Comments usually starts with a # (hash symbol) then Python interpreter ignores them.
# Single Line Comment
print("Hello, World!")
You can place comments at the end of a line, and Python will ignore the rest of the line.
print("Hello, World!!") #Single Line Comment
Both above will produce following result:
Hello, World!!
Multi Line Comment
Python does not really have a syntax for multi line comments. Python does not really have a syntax for multi line comments. To add a multiline comment there are two approaches.
To add a multiline comment you can insert a # for each line.
#This is multi line comment demo #This is a comment #written in #more than just one line print("Hello, World!!")
As you know Python ignores 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.
""" This is a multi line comment demo This is a comment written in more than just one line """ print("Hello, World!!")
As you haven’t assigned string to a variable, Python will read the code, but then ignore it. Finally, you have made a multiline comment.
Previous : Python – Basic Syntax
1 thought on “Python Comments”