Home Micropython Python Basics : Comments

Python Basics : Comments

by shedboy71

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

Let’s 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

MicroPython v1.9.2-34-gd64154c73 on 2017-09-01; micro:bit v1.0.1 with nRF51822
Type "help()" for more information.
>>>
>>> Hello, World!

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

MicroPython v1.9.2-34-gd64154c73 on 2017-09-01; micro:bit v1.0.1 with nRF51822
Type "help()" for more information.
>>>
>>> Hello, World!

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

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

Once again the output will be

MicroPython v1.9.2-34-gd64154c73 on 2017-09-01; micro:bit v1.0.1 with nRF51822
Type "help()" for more information.
>>>
>>> Hello, World!

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

MicroPython v1.9.2-34-gd64154c73 on 2017-09-01; micro:bit v1.0.1 with nRF51822
Type "help()" for more information.
>>>
>>> Hello, World!

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 comment:

 

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

or

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

Both of these examples display the same output

 

MicroPython v1.9.2-34-gd64154c73 on 2017-09-01; micro:bit v1.0.1 with nRF51822
Type "help()" for more information.
>>>
>>> Hello, World!

You may also like