Comments in Python

The purpose of comments is to explain what is happening in the code.

Comments are written along with your code but do not influence your program flow.

When you work by yourself, maybe comments don’t feel like something you should write, you know the whys of every single line of code.

But what if you need new people to board in your project after a year and the project has 3 modules, each with 10,000 lines of code.

Think about people who don’t know a thing about your app and having to maintain it, fix it, or add new features.

Remember, there is no single solution for a given problem, your way of solving things is yours and yours only, if you ask 10 people to solve the same problem, they will come up with 10 different solutions.

If you want others to fully understand your reasoning, a good code design is mandatory, but comments are an integral part of any codebase.

How to Write Comments in Python

The syntax of comments in Python is rather easy, just use the hash mark # symbol in front of the text you want to be a comment.

#This is a comment and it won't influence my program flow

You can use a comment to explain what some function does.

#Returns the sum of any given two numbers
def sum(a, b):
    return a + b

Or be more specific and write inline comments for some quirks in your code.

#Calculates the cost of the project given variables a and b
def cost(a, b):
    return a + b*10 #10 is the empirically tested order of magnitude

Multiline Comments

Maybe you want to comment on something very complex or describe how some process works in your code.

In these cases, you can use multiline comments.

To do that, just use a single hash mark # for each line.

#Everything after the hash mark # is a comment
#This is a comment and it won't influence my program flow
#The comment below explains what the function does

#Calculates the cost of the project given variables a and b
#a is the time in months it will take until the project is finished
#b is how much money it will cost per month
def cost(a, b):
    return a + b*10 #10 is the empirically tested order of magnitude

Conclusion

Comments are important and as a programmer, you must develop the habit of commenting on your code.

It will help your peers understand the project or just refresh your memory about that logic you created a couple of years ago and makes no sense to you anymore.