- Python Comment: What It Is And How to Create
- What is a Python comment?
- A single-line Python comment
- Multiline Python comment
- Comment out code
- Common mistakes with Python comments
- Using too many comments
- Stating the obvious
- Not maintaining your Python comments
- Commenting out code instead of removing it
- Keep learning
- Get certified with our courses
- 2 thoughts on “Python Comment: What It Is And How to Create”
- Leave a Comment Cancel reply
- Comments in Python: Why are They Important And How to Use Them
- What Are Comments in Python Used For?
- Basics to Advanced — Learn It All!
- What Are the Advantages of Using Comments in Python?
- What Are the Different Types of Comments in Python?
- Single-Line Comments
- Multi-Line Comments
- Career Roadmap to Becoming Blockchain Developer
- Python Docstrings
- How to Write Good Comments in Python?
- Conclusion
- Find our Post Graduate Program in Full Stack Web Development Online Bootcamp in top cities:
- About the Author
- Recommended Programs
Python Comment: What It Is And How to Create
A Python comment is an explanation in the source code of a Python program. It doesn’t do anything besides being informative and is ignored by the Python interpreter. In this article, you will learn:
- what Python comments are,
- how to add comments to your Python code,
- what the common pitfalls are when writing comments
What is a Python comment?
Let’s start by defining what a comment is exactly:
Comment A comment is an explanation in the source code of a Python program. Comments are added with the purpose of making source code easier for humans to understand. They are ignored by the Python interpreter.
So, in short, a comment helps you and other readers of your code to better understand it.
A single-line Python comment
In Python, we create a comment by starting the line with the hash symbol: #. This symbol is known as the number sign, hash, or (in North American usage) pound sign. Whatever you call it, this is what it looks like:
# This is a single-line comment in Python print('Hello') # And here's another one!
Multiline Python comment
There’s no special way to add multi-line comments, also called block comments. Instead, you simply use the hash symbol at the start of each line, like so:
# This is a multi-line comment in Python, # there's not much difference with single- # line comments, as you can see!
In Python (or any language, for that matter), it’s better to write clear, understandable code. So if you’re doing well, you should not need multi-line comments that often!
Comment out code
A pattern that programmers use a lot, is commenting out code temporarily. There are countless reasons why one might want to do this. Here are just a couple of examples:
- A piece of functionality is not working right now, but you plan to work on it later so you don’t want to throw it away
- There’s an alternative piece of code that you might want to use later on, so you leave it as a hint in a comment
- You’re refactoring your code, meaning you’re cleaning up the code. Often, this is a process where you create more and smaller functions, while you’re not completely ready to throw away the old code.
To comment out code in Python, we again use the hash symbol:
# This code is disabled for now # if password == 'welcome123': # allow_access()
Tip: In most IDEs and editors, you can comment out multi-line blocks of code by selecting all the lines and pressing Ctrl + /. You can reverse the operation by doing exactly the same.
Common mistakes with Python comments
There are a few mistakes that many programmers make when it comes to comments. Therefore, let’s explore these, so you hopefully won’t make them!
Using too many comments
You should limit the use of comments to what is absolutely necessary. Why is that?
There’s a concept called self-documenting code. This means that your code is so readable and easy to understand that comments or documentation are hardly needed. If your code is readable and you don’t need comments, it’s more compact and easier to read. Hence, it would be best if you always strived to write self-documenting code and only resort to comments to explain the more advanced or non-obvious things.
Writing self-documenting code deserves its own article, but there are three key takeaways that already can help a lot:
- Name your Python variables so that it’s abundantly clear what they contain. E.g., don’t name your list just m, or m_list, but instead, call it something like member_list.
- Name your Python functions concisely so they clearly describe what they do. Put a verb in there if you can, like get_user, or add_item.
- Create short functions that only do one thing. If they do more than one thing, split them into multiple functions. Short functions are also better once you start using unit tests.
Stating the obvious
Many beginning programmers tend to state the obvious. In other words, they describe in comments what they are about to do. You too might be tempted to do so, especially when a language is new to you, as a note to yourself.
Here are some examples of stating the obvious:
# Ask for the user's name name = input('Name: ') # Call the say_hi function say_hi(name) # Now we divide the user input by 100 result = input / 100
Not maintaining your Python comments
While editing your code, it’s easy to forget the comments that are there. Always check if they still apply or perhaps need a touch-up because you just changed the code.
It’s a common mistake to forget comments that describe a function or a class because they are often not very close to the code you’re editing. After refactoring your code, always take a look at the comments.
Commenting out code instead of removing it
As stated above, sometimes you need to comment out code. But that doesn’t mean you can just leave it there. In my professional life as a programmer, I’ve seen (too) many commented-out sections of code. The problem with this is that nobody dares to touch it. Your colleague must have left it there for a reason, right?
No… your colleague probably just forgot about it. But can you be sure? For this reason, make a habit of cleaning up code that is commented out.
Keep learning
You may also be interested in my tutorial on Python docstrings.
Get certified with our courses
Learn Python properly through small, easy-to-digest lessons, progress tracking, quizzes to test your knowledge, and practice sessions. Each course will earn you a downloadable course certificate.
2 thoughts on “Python Comment: What It Is And How to Create”
Hi there, First of all this tutorial is amazing 🙂 I cannot seem to work out how to comment out my code. I am using IDLE shell 3.11.1 on a MacBook Air. I added a comment using the #, then tried to remove it using: Ctrl + /
Ctrl 3/4
and many others that I found online 🙂 The comment stays there with the #. Just wondering if there is something I am not understanding? I also tried to turn pre-existing and functional code into a comment, is this something that can/should be done or is this irrelevant? Thank you!! Log in to Reply
In IDLE, the shortcut to use is control + D. In the Shell, commenting out code doesn’t have much use. You’re working on one line at at time anyway. Comments are more suited when creating files. Not sure what you mean by your last remark, though! In general, I’d use comments to add the ‘why’ to your code (the ‘how’ is shown by your code itself). Commenting out actual code should be temporary. If it’s permanent, you better remove it and trust version control (git) to keep a history of it in case you need it later. Log in to Reply
Leave a Comment Cancel reply
You must be logged in to post a comment.
You are browsing the free Python tutorial. Make sure to check out my full Python courses as well.
Subscribe to my newsletter for Python news, tips, and tricks!
Comments in Python: Why are They Important And How to Use Them
Comments in Python is the inclusion of short descriptions along with the code to increase its readability. A developer uses them to write his or her thought process while writing the code. It explains the basic logic behind why a particular line of code was written. They are just meant for the coders themselves or other developers to understand a piece of code, especially since the Python interpreter completely ignores comments in Python. You can see this in the following example.
What Are Comments in Python Used For?
Comments in Python are identified with a hash symbol, #, and extend to the end of the line. Hash characters in a string are not considered comments, however. There are three ways to write a comment — as a separate line, beside the corresponding statement of code, or as a multi-line comment block.
There are multiple uses of writing comments in Python. Some significant uses include:
- Increasing readability
- Explaining the code to others
- Understanding the code easily after a long-term
- Including resources
- Re-using the existing code
Basics to Advanced — Learn It All!
What Are the Advantages of Using Comments in Python?
Comments in Python provide numerous advantages. Their primary benefits include:
- Makes the code easily understandable by other programmers
- The code becomes self-explanatory
- Helps remember why we used a specific command, method, or function in the code
- Enables the interpreter to ignore some part of the code while testing
What Are the Different Types of Comments in Python?
There are three types of comments: single-line, multi-line, and docstring comments. The syntax of comments varies depending on the type. This tutorial will explore every kind of comment individually, along with examples.
Single-Line Comments
Single-line comments begin with the “#” character. Anything that is written in a single line after ‘#’ is considered as a comment. The syntax for writing single-line comments is:
There are two ways of using single-line comments in Python. You can use it before the code or next to the code. The example depicted below shows the use of comments in both ways.
PEP8, Python Style Guide, recommends using less than 79 characters in a single-line comment to make it easier to read. If your comment is exceeding the recommended length, you can use the next type: multi-line comments.
Multi-Line Comments
Python does not support multi-line comments. However, there are multiple ways to overcome this issue. None of these ways are technically multi-line comments, but you can use them as one. The first way is by using # at the beginning of each line of the comment.
The next way is by using string literals but not assigning them to any variables. If you do not assign a string literal to a variable, the Python interpreter ignores it. Use this to your advantage to write multi-line comments. You can either use a single (‘’) quotation or double (“”) quotation.
You can also use multi-line strings for commenting. To do this, use either a ‘’ or “” quotation marks three times.
Career Roadmap to Becoming Blockchain Developer
Python Docstrings
Python provides an in-built feature called docstrings for commenting on modules, methods, functions, objects, and classes. They are written in the first line after defining a module, function, method, etc., using three quotation marks (‘’ or “”). If you do not use it in the first line, the interpreter will not take it as a docstring. You can also access docstrings using the __doc__ attribute.
How to Write Good Comments in Python?
Comments are a crucial part of a program. Hence, it is essential to learn how to write good comments. Here are some characteristics that define good comments.
- Ensure that they are concise
- Don’t write generic comments; only have them if they add information
(a=10 #assigning 10 to a, avoid writing such generic comments)
- Write comments that describe the overall task of a function or method and not specific details
- Good comments are self-explanatory
- Don’t write redundant comments
Learn right from the basics of JavaScript to advanced concepts of Angular, Spring Boot, Hibernate, JSPs, MVC, etc. Enroll in our PGP in Full Stack Web Development today!
Conclusion
With that, we have come to the end of the ‘Comments in Python’ tutorial. Writing good comments in Python will allow other programmers to read and understand your code easily. It is one of the many basic concepts in Python that you must learn to grasp the programming language. With our Python tutorial for beginners’ playlist, you can easily learn everything about comments and other concepts in Python.
Have any questions for us? Leave them in the comments section, and our industry experts will get back to you on the same, as soon as possible!
Find our Post Graduate Program in Full Stack Web Development Online Bootcamp in top cities:
Name | Date | Place | |
---|---|---|---|
Post Graduate Program in Full Stack Web Development | Cohort starts on 15th Aug 2023, Weekend batch | Your City | View Details |
Post Graduate Program in Full Stack Web Development | Cohort starts on 12th Sep 2023, Weekend batch | Your City | View Details |
Post Graduate Program in Full Stack Web Development | Cohort starts on 10th Oct 2023, Weekend batch | Your City | View Details |
About the Author
Ravikiran A S
Ravikiran A S works with Simplilearn as a Research Analyst. He an enthusiastic geek always in the hunt to learn the latest technologies. He is proficient with Java Programming Language, Big Data, and powerful Big Data Frameworks like Apache Hadoop and Apache Spark.
Recommended Programs
Post Graduate Program in Full Stack Web Development
Full Stack Web Developer — MEAN Stack
Automation Testing Masters Program
*Lifetime access to high-quality, self-paced e-learning content.