Programming with Python is exciting. Writing code and sharing it with others can lead to amazing things. But before our programs can grow, we need to make sure they are easy to read. That’s why programmers learn how to comment a block of code.
Why is it important to make our code readable? The simple answer is that code is read more than it is written. In order to ensure that our code is maintainable, we need to make it clear to others what is going on.
For this reason, comments are a necessary part of writing readable code. Writing comments gives us a chance to explain what a block of code does. We use them to explain what would otherwise be confusing or obscure parts of a program.
We can also use comments to remove parts of a program for testing purposes. By blocking out a line of code, we can prevent it from being compiled. This allows us to test alternative logic or troubleshoot our programs.
Why Writing Comments is Important
As a project grows, it becomes necessary to expand. This means a larger codebase and a larger team. For that team to function correctly, everyone needs to be on the same page.
Poor choices early on can lead to code that is difficult to maintain. And without comments to help decipher the code, it can be challenging for new developers to get up to speed. You don’t want your coworkers tearing out their hair trying to figure out what some badly named variable does.
And even if you are working alone, writing software in solo-mode, it’s a good idea to put some comments in the program. Why? Chances are, when you come back to the program in a month or two, you won’t remember exactly how everything works. This is especially true with a large program, spanning multiple files.
What is a Block of Code?
In general, a block of code refers to multiple likes of code that are grouped together. This can include several statements as well as comments. In Python, blocks of code rest on the same indentation level.
Example 1: Identifying a Block of Code in Python
def print_upper_case(name):
# these statements make up a single block
upper = name.upper()
print(upper)
print_upper_case("taylor") # outside of the block
Output
TAYLOR
In this example, we’ve identified the block of code that lies below the print_upper_case() function. This block of code begins with a comment, followed by two more statements. The function call at the bottom is outside the aforementioned block of code.
Do we really need multiline comments?
There are times when commenting out an entire block of code can be useful. For instance, if we need to troubleshoot a part of the code and we’d like to see what happens if some block doesn’t execute.
In such an instance, it can be convenient to comment out an entire block of code. That way we don’t lose what we’ve already written.
Furthermore, while it’s wise to keep comments short, sometimes we need more than one line to say what we need. In such a case, it’s good to use a block comment.
Using #’s to Comment a Block of Code
The most straight-forward way to comment out a block of code in Python is to use the # character. Any Python statement that begins with a hashtag will be treated as a comment by the compiler.
There’s no end to how many block comments you can have, in a row or otherwise. This can be useful if we need to make a multiline comment.
Example 1: Writing Messages
def message_writer(msg):
# We may need to do it this way in the future
#new_msg = "Message Writer says: "
#new_msg += msg
#print(new_msg)
print("Message Writer says: " + msg)
message_writer("Lovin' it!")
Output
Lovin' it!
In the example above, we’ve used block comments to temporarily hide some of the Python statements from the compiler. By adding a # before each statement, we’ve effectively removed it from the code.
Perhaps we have a Python program that is used by developers. It is a system’s settings file. Depending on their needs, some lines of code may need to be removed from the program. Using block comments means we can give these developers several options that they can effectively “turn on” by simply uncommenting those statements.
How to Use Docstrings to Make Block Comments
While block comments technically allow us to make multiline comments, using them can be cumbersome. This is especially true if the block of code is longer than a few lines. Having to add and remove hashtags isn’t any fun.
Luckily, there’s another way to create multiline comments in Python. We can do this using docstrings (Document Strings).
Docstrings allow us to quickly comment out a block of code. We can create a docstring in Python using sets of triple quotes. This method has been approved by Guido Van Rossum, the creator of Python. Here’s a quote about about using docstrings to make comments from Guido’s Twitter page:
Python tip: You can use multi-line strings as multi-line comments. Unless used as docstrings, they generate no code! 🙂
-Guido Van Rossum
It’s important to keep in mind that docstrings aren’t really comments, they’re strings that aren’t assigned to a variable. Unassigned strings are ignored at runtime, so they will serve the same function as comments for our purpose.
However, docstrings have another purpose in Python. Place after a function or class declaration, a docstring will serve as a piece of documentation associated with that object. Used in this context, docstrings serve as a quick way of generating an API (Application Program Interface).
Alternative Methods of Commenting Out Code in Python
Block comments and docstrings are the only means of creating comments in Python. If you’re like me, neither method is exactly what you want in every scenario.
Fortunately for us, we don’t have to rely entirely on Python’s tools. Using today’s technology, it’s possible to create multiline comments with the click of a mouse.
Use an IDE or Text Editor
Unless you’re writing code in Notepad, you probably have access to tools that allow you to comment out a block of code. While this method isn’t explicit to Python, it’s a common practice in the real world.
Using an IDE (Integrated Development Environment), it’s possible to comment entire lines of code at once. In many cases, these special features can be accessed from the toolbar. These features will be specific to each IDE, so you’ll need to do some research depending on what software you’re using to write your Python code.
Most Text Editors have a feature that allows you to comment out several lines of code at once. If you search for a Text Editor that was created specifically for developers, it will likely have this feature.
Examples of Using Multiline Comments in Python
To help illustrate when and how to use block comments and docstrings, we’ve included a few more examples.
def add_square(x,y):
a = x*x
b = y*y
return a + b
print(add_square(2,2))
The add_spare() function we’ve written uses a block of code that requires several lines to complete the desired calculation. This block could be rewritten with a single line. We’ve commented out the old lines so that you can compare the two methods.
def add_square(x,y):
#a = x*x
#b = y*y
#return a + b
return (x*x) + (y*y)
print(add_square(2,2))
Docstrings are used to define a function, class, or module. We can read docstrings using __doc__ attribute.
def product(x,y):
'''Returns the product of the given arguments.'''
return x*y
x = 4
y = 3
print("{} x {} = {}".format(x,y,product(x,y)))
print(product.__doc__)
Output
4 x 3 = 12
String literals, on the other hand, look like docstrings, but they don’t work in the same way. Instead, they are ignored when the program runs. Because of this, we can use them as multiline comments.
"""
The Fibonacci series is a sequence of numbers where each
term is the sum of the previous two terms.
Starting with 0 and 1, we can compute the nth term in the sequence.
"""
def fib(n):
a,b = 0,1
for i in range(n):
a,b = b,a+b
print(a)
return a
print(fib(10))
Tips for Commenting in Python:
- Keep comments short and concise.
- Always be respectful and helpful.
- Remember, the best code explains itself by using good names for variables, functions, and classes.
Summary
While it’s true that Python doesn’t support multiline commenting in the way some other programming languages do, it’s still possible to create these types of comments is the # character. Block comments are a standard way of creating multiline comments in Python. They can also be used to comment out a block of code from a program.
If block comments aren’t sufficient, it’s also possible to create a multiline comment using docstrings. Docstrings will generate no code unless they are used in special ways.
Lastly, it’s possible to use modern IDE’s to comment out a block of code. This method will depend on the software you’re using, but it’s generally a fairly easy procedure. Some programs even have hotkeys dedicated to commenting and uncommenting blocks of code.
Related Posts
- How Python try except statements can catch errors in your code
- How to use a Python dictionary to store key value pairs
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.