Learn about comments and how to create them in the Python language.
As it pertains to programming, comments are essentially detailed notes that are strategically placed in order to describe certain parts of code. They help to facilitate better understanding when other programmers review your code. They’re also extremely beneficial to the creator of the code as well.
For simple lines of code that require very little explanation, placing a #
just before the line of code in question will suffice! In the example below, note that the single line comment asking the programmer to create a user’s input is grayed out. This indicates that the comments you create have been ignored by the program and will not run.
This can be simplified even further! If you find yourself in a situation where even less explanation is needed, you can implement what is known as an in-line comment. Very similar to the aforementioned format, this type of comment also begins with a #
. However, as the name suggests, it is in-line and placed directly next to the portion of code in question. Once, you’ve written your code, no other #
or characters are necessary at the end of the line.
As with any programming language, syntax in Python is very important. In the above examples, you may notice that there is a space between the #
and the comment’s text. While creating a space is not required, it’s always beneficial to practice proper coding etiquette by establishing consistency throughout your code. For instance, if you choose to type your comments without a space, it’s a good idea to follow that same format throughout your entire code!
There may come a time when you’re tasked with coding a program that requires a Top-Down approach. Part of this approach is to ensure that each step of the code is concise and easy to follow. This is where incorporating multi-line comments comes in handy!
There are a few ways to create multi-line comments. The method you choose is completely up to you. Just keep in mind consistency throughout your code.
Triple Quotes
Wrapping your code with two sets of triple quotes ("""
or '''
) is a great way to take multiple lines of comments. To do this, simply place one set of triple quotes in front of the first line of comments and another set after the last line of comments.
There is one more approach to making multi-line comments. In the likeness of single line comments, you would simply place a #
at the beginning of each line of comments you create.
Ultimately, what you decide to write for the comments is your choice. Aside from syntax, the most important thing is making sure the next person (including yourself) to read the program, understands what exactly the code is doing. Take a look at the coding editor below. Let’s check your understanding by practicing the following tasks!
Try It Out!
"""
to '''
and try altering their beginning and ending positions.speed(0)
, change the comment to explain what it does.