For more information on concepts covered in this lesson, you can check out:
Leave Helpful Comments
00:00 In this lesson, you’re going to learn how to leave yourself helpful notes. They’re called comments. Programmers sometimes read code that they wrote a while ago and wonder, “What does this do?” When you haven’t looked at code in a while, it can be difficult to remember why you wrote it the way that you did. To help avoid this problem, you can leave comments in your code.
Comments are lines of text that don’t affect the way the program runs. made certain decisions. If you open your previous file,
hello_world.py, to start a comment, you use the hash symbol (
#), sometimes called the number sign.
00:47 You might’ve heard that. Start with that hash symbol, and then anything you write after that is going to be ignored when the program is run. So if I save and then run this code, you can see that it just ran as it did normally. It didn’t change anything about how this particular code runs.
You can still use that pound sign, the hash symbol, inside of a string. For instance, Python won’t mistake the following for a string. Let me go back to the interactive window. If I were to, say, print a string saying
"#1", it won’t have a problem with that.
01:47 In general, it’s a good idea to keep your comments as short as possible, but sometimes you need to write more than reasonably fits on a single line. In that case, you can continue your comment on a newline and also begin it with a hash symbol.
02:03 You can also comment out lines of your code. To do this, you place that hash/number sign at the beginning of a line of code. It’s a nondestructive way to test the behavior of your program without it running specific lines of the code. Let me show you what that looks like.
02:21 To comment out a section of code in IDLE, you highlight the lines and press: for Windows, you hold the Alt key and press 3. On a Mac, hold Ctrl and press the number 3. On Ubuntu Linux, you can hold Ctrl and press D.
02:59 So again, here on my Mac, I’m going to highlight those lines of code and use Ctrl+4 to uncomment. It’s a good way to test out certain things within your program with or without a particular line of code.
03:24 They should have a single space between the hash symbol and the first word of the comment. Inline comments should start with two spaces after your code. PEP 8 also recommends that your comments are used sparingly. Comments that actually describe what is already obvious are unnecessary and can be a big pet peeve of many programmers. Comments are best used to clarify code that may be difficult to understand or to explain why something is coded in certain ways. Okay, up next is a summary, and I’m going to share some additional resources for you.
Become a Member to join the conversation.