Writing code in Python can be challenging. That’s why it’s important to be as clear as possible when naming variables and functions. A good name will explain what a variable is used for, or what a function does. However, good naming conventions will only get you so far. What if we’re dealing with complex logic or an otherwise confusing algorithm? Or what if we need to share and explain our intentions with another programmer? It would be helpful to leave notes for ourselves, or others, in the code. That’s what Python comments are for.
With comments, we can make our programs easier to understand, and easier to make changes to later. Python comments are ignored by the interpreter, so they won’t interfere with how your code runs.
Topics we’ll cover:
- Why writing comments is important
- How to use comments to improve your Python code
- Best practices for commenting in Python
When to Write Python Comments?
Let’s face it, programming isn’t easy; we could all use some help. Comments allow a programmer to add some extra information that explains what’s happening in the code.
If you’re working on a large project, it can be difficult to keep track of everything that’s going on. This is especially true when returning to a project after a long absence.
Such a scenario is more common than you might think. Programmers are often required to juggle many projects at once.
Coming back to a project is often painful. Updating a project is much easier if the code is clear, follows styling guides, and makes use of well placed comments.
When it comes to working on a team, comments are even more crucial. It can be hard enough to decipher your own code, let alone something written by a coworker, or stranger. Following some basic guidelines will help you write clear, effective comments.
How to Write a Comment in Python?
Comments are usually written in blocks and explain the code that follows them. Typically, comments are used to explain complex formulas, algorithms, or design decisions.
Definition: A comment is code that is meant to be programmer-readable, and ignored by the computer. It’s a message to ourselves, or other coders working on a project.
Usage: Use comments to explain functions, algorithms, maths, design choices, or anything else you may need to refer to in the future.
Syntax: Most comments in Python are written using the # characters. Python ignores any code that follows a hash sign (#) when the program runs.
There are three different types of comments available in Python: block, inline, and docstring. Knowing when to use each is important. For instance, docstrings can be used to automatically generate the documentation for a project.
Writing Single Line Comments in Python
A single line comment, known as a block comment in Python, starts with the # character. The block comment is used to explain code that follows the comment.
Remember to keep comments as short as possible. It’s easy to overdo it, adding comments about everything under the impression that the program becomes clearer the more words there are. That isn’t true.
Brevity is the soul of wit, as they say. The same is true of commenting your code. It’s a good idea to keep it simple.
Example 1: Python block comments
# this is a block comment in python, it uses a single line
# a list of keywords provided by the client
keywords = ["tv shows", "best streaming tv","hit new shows"]
Example 2: The Pythagorean Theorem
import math
# the sides of a triangle opposite the hypotenuse
a = 2
b = 3
# the Pythagorean Theorem
c = math.sqrt(a**2 + b**2)
print(c)
Output
3.605551275463989
Inline Comments
In order to save space, it’s sometimes a good idea to put a comment on the same line as the code you’re describing. This is known as an inline comment.
Inline comments are also written with the # character. They are placed at the end of a code statement. Inline comments are useful when you want to include more information about variable names, or explain a function in greater detail.
Example 3: Writing Inline Comments in Python
income = 42765 # annual taxable income in USD
tax_rate = 0.22 # 22% annual tax rate
print("You owe ${}".format(income*tax_rate))
Writing Multiline Comments in Python
In Python, the most direct path to writing a comment that’s more than one line long is to use multiple block comments. Python will ignore the hash signs (#) and you’ll be left with multiple lines of comments.
Example 4: Multiline Comments
chessboard = {}
# we need to use a nested for loop to build a grid of tiles
# the grid of tiles will serve as a basis for the game board
# 0 will stand for an empty space
for i in range(1,9):
for j in range(1,9):
chessboard[i,y] = 0
Unfortunately, with this method it’s necessary to add a hashtag before every line.
While you can’t technically write a comment that’s longer than a single line, Python docstrings offer a way of getting around this rule.
Docstrings are meant to be associated with functions and classes. They’re used to create documentation for your project as the docstring will become associated with the functions they appear under.
Docstrings use two sets of triple quotes to designate that the text between them is special. These triple quotes are meant to be placed after functions and classes. They are used to document Python code.
Example 5: Using a docstring with a Function
def string_reverse(a_string):
"""A helper function to reverse strings
Args:
a_string (sring):
Returns:
string: A reversed copy of the input string
"""
reverse = ""
i = len(a_string)
while i > 0:
reverse += a_string[i-1]
i = i-1
return reverse
# driver code
print(string_reverse("Is this how you turn a phrase?"))
Output
?esarhp a nrut uoy woh siht sI
We can also use these triple quotes to create comments in Python. Because they are read as strings, they won’t affect our program when it runs.
""" this is a multiline comment in Python
it's basically just a string
but you have to be careful when using this method.
"""
Suggested Reading: To read about more computer science topics, you can read this article on dynamic role-based authorization using ASP.net. You can also read this article on user activity logging using Asp.net.
Making Comments For Yourself
Some comments are left for the developers themselves. For instance, you might leave a comment to remind yourself where you left off on something you were unable to finish on a previous work day.
Large programs are difficult to manage. When you open a project, especially if it’s one you haven’t looked at in a while, you’ll sometimes find that you need to “reload” the code. Essentially, you’ll need to remind yourself of the details of the project.
Comments can help save time in this regard. Some well placed comments can help you avoid those head-scratching moments where you ask, “What exactly was I doing here?”
Commenting for Others
Anytime you’re working on a team, Python or otherwise, communication is vital. Confusion here only leads to wasted time and frustration.
That’s why programmers should use comments to explain their code. Following style guides and appropriately commenting your work will make sure everyone is on the same page.
If you are into machine learning, you can read this article on regression in machine learning. You might also like this article on polynomial regression using sklearn in python.
Best Practices for Commenting in Python
While Python comments usually make a program easier to understand, that isn’t always the case. There are some unwritten rules that one should follow if they hope to write productive comments.
It’s true that adding more comments doesn’t necessarily improve your code’s readability. In fact, having too many comments is just as bad as having too few. So how do you know how much to comment, when to comment, or when NOT to comment?
Commenting Guidelines:
- Avoid redundancy
- Be respectful
- Less is more
Knowing when comments are unnecessary is an important skill to master. Often, you’ll see students repeat function names in variables, as if writing them again will make their meaning clearer.
Don’t make unnecessary comments like this one:
# the name of the author
author_name = "Le Guin, Ursula K"
Let’s take a look at a longer example with multiple comments and a docstring. Use the comments to navigate the bubble sort algorithm.
Example 7: Commenting the bubble sort algorithm
def BubbleSort(nums):
"""A method for quickly sorting small arrays."""
total_nums = len(nums)
for i in range(total_nums):
for j in range(0, total_nums-i-1):
# traverse the array backwards
# swap elements that are out of order
if nums[j] > nums[j+1]:
temp = nums[j]
nums[j] = nums[j+1]
nums[j+1] = temp
nums = [100,7,19,83,63,97,1]
BubbleSort(nums)
print(nums)
Output
[1, 7, 19, 63, 83, 97, 100]
Helpful Links
Hopefully I’ve impressed upon you the importance of properly commenting your Python code. It will save you time and make your work easier.
Hungry for more? Sharpen your Python coding skills by following these links to more Python For Beginners tutorials.
Recommended Python Training
Course: Python 3 For Beginners
Over 15 hours of video content with guided instruction for beginners. Learn how to create real world applications and master the basics.