Home » Comments in Python

Comments in Python

by maxguy71

Comments serve a few purposes such as explaining what a particular piece of code does, it can also make your code more readable and make it easier for other programmers to understand what the code does and you can also use comments to implement basic debug by commenting out a line of code which will prevent it executing

Lets look at some basic examples, remember in this scenario a comment on this one line of code would be overkill

We used the Mu editor for these examples

#This is a comment and will not be displayed
print("Hello, World!")

You should see the following

You can put a comment on the same line after a statement or expression like this

print("Hello, World!") #This is a comment and will not be displayed

And again you should see something like this

In this example we have commented out a line of code as if to ‘debug’ it and stop it executing

print("Hello, World!")
#print("This will not be displayed")

Once again the output will be

Unlike other programming languages there is no concept of multi-line comments, you can simply add a # for each line you want to comment out, lets see this

#This is a comment
#this is another one
#and another one
print("Hello, World!")

And again you will see this

There is also another trick that you can use in that a triple-quoted string is ignored by the Python interpreter and can be used as a multiline comments:


'''This is a comment
this is another one
and another one'''
print("Hello, World!")


This is a comment
this is another one
and another one
print("Hello, World!")

Both of these examples display the same output

You may also like

Leave a Comment

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More