A Beginner’s Guide to Python for Data Science - Part 5 Adding Comments in Python
Next, let’s discuss commenting in Python.
Comments are descriptions of the code under consideration. So we can write one or more lines of explanation.
There can be times when you need to write some long and complicated code for a task. After it is complete, you might save the file somewhere, but when you refer to the code sometime in the future, let’s say, after three or four months, you may not be able to understand the code you have written yourself!
To help yourself and anyone going through your code, in the hope of understanding its utility, you should generously use comments to clarify the written code.
Commenting is necessary, especially for the complicated functions you might have created for a specific task.
There are a few ways to declare a comment inside Python. The easiest way is to use a hash symbol (#).
When we use the hash symbol inside our code, the python interpreter ignores whatever is present after the hash sign.
Let’s take the example where we used the “for loop” to print the first ten numbers. Now, say we are sharing this code with someone who doesn’t understand how “for loops” work and what should be the expected output. We can help the person by writing a comment just before the code, as shown below:
# A for loop to print the numbers from 1 to 10
for i in range(1, 11):
print(i)
You can observe that when you run the above code, Python does not complain about the explanation we have written because it just ignores it, thanks to the hash symbol.
for i in range(1, 11):
print(i)
You can observe that when you run the above code, Python does not complain about the explanation we have written because it just ignores it, thanks to the hash symbol.
Let’s write the previous comment in multi-lines.
# A for loop to print
# the numbers from 1 to 10
for i in range(1, 11):
print(i)
The second method to write multi-line comments is via the use of triple quotes, as shown below:
# the numbers from 1 to 10
for i in range(1, 11):
print(i)
The second method to write multi-line comments is via the use of triple quotes, as shown below:
'''A for loop to print
the numbers from 1 to 10'''
for i in range(1, 11):
print(i)
So, whenever you need to write a multi-line comment for any code, my suggestion is the triple quotes for the task. It would be easier to comment using them than the hash symbol on every line.
the numbers from 1 to 10'''
for i in range(1, 11):
print(i)
So, whenever you need to write a multi-line comment for any code, my suggestion is the triple quotes for the task. It would be easier to comment using them than the hash symbol on every line.
And there we have it.If you found this useful, you can check the below book and have a copy for yourself by going to :
Thank you for reading.
Until next time!
#Python #Data Science #Data Science Training #Learn Python
Comments
Post a Comment