/    /  Python – Comments

Python – Comments

In this tutorial you will learn python in detail.


Comments another awesome and easy way to make your Python code easily understood by others. Comments need not have to be text to explain the code, it might also be used to prevent Python from executing code:

let’s take a quick look at why commenting your code is so important.


Why Commenting Your Code Is So Important?


Scenario A: It is common that developers forget their own code all the time, especially if it was written a long time ago. They spend lots of hours trying to parse through what they wrote.

Scenario B: When a new developer enters into your project to work as a team, the new developer needs to spend lot of time to understand the code line by line. The new ones spend hours of time to figure out how it works.

So, in order to make Python code understandable commenting is a great way to practise and to prevent above scenarios.


Python Commenting Basics


Developers need commenting. Simply put the hash mark ‘#’ before your desired comment, in order to write a Python comment.


# This is a comment


Everything after the hash mark till the end of the line will be ignored by Python. You can add them anywhere in your code, even inline with other code:


print("This will run.")  #This won't run


In the above code everything after hash will be ignored.


Python Multiline Comments


Like other programming languages Python doesn’t have a way to write multiple comments. But there are two simple ways to write multiple comments in Python.

The first way is pressing the return key after each line, add a new hash mark and continue your comment from here.


def multiline_example():
# This is a pretty good example
# of how you can spread comments
# over multiple lines in Python


The second way is to placing your lines in triple quotes, as shown below:


If I really hate pressing `enter` and
typing all those hash marks, I could
just do this instead


How to Practice Commenting?


The simplest way is to start writing comments for yourself in your own code. Include simple comments where necessary.

Another good way is going back to your old code, review it by writing comments to help clarify the code’s purpose.

Learning to comment will no doubtedly make you gain a deeper understanding of Python as well.

Using comments will also make you to modify your poor written code into more robust one.