Page 59 - Python Basics: A Practical Introduction to Python 3
P. 59
3.5. Leave Yourself Helpful Notes
3.5 Leave Yourself Helpful Notes
Programmers sometimes read code they wrote a while ago and won-
der, “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 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 a program runs.
They document what code does or why the programmer made certain
decisions.
How to Write a Comment
The most common way to write a comment is to begin a new line in
your code with the # character. When you run your code, Python ig-
nores lines starting with #.
Comments that start on a new line are called block comments. You
can also write inline comments, which are comments that appear
on the same line as the code they reference. Just put a # at the end of
the line of code, followed by the text in your comment.
Here’s an example of a program with both kinds of comments:
# This is a block comment.
greeting = "Hello, World"
print(greeting) # This is an inline comment.
Of course, you can still use the # symbol inside a string. For instance,
Python won’t mistake the following for the start of a comment:
>>> print("#1")
#1
In general, it’s a good idea to keep 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 new line that also
begins with the # symbol:
58