Computer Science · Ch 5 — Getting Started with Python
Comments
Comments
Comments are remarks or notes added inside source code. The interpreter does not execute comments — they exist purely for the humans reading the program.
Why comments exist
Comments make source code easier for people to understand. Their primary uses are to document:
- the meaning and purpose of the source code, and
- its input and output requirements,
so that we can remember later how the program functions and how to use it. The need becomes acute on large and complex software: programmers work in teams, and a program written by one programmer is often used or maintained by another. In those situations, documentation in the form of comments is what lets the second programmer understand how the program works.
Comment syntax: the hash sign
In Python, a comment starts with # (the hash sign). Everything from the # to the end of that line is treated as a comment, and the interpreter simply ignores it while executing the statement.
The textbook's Example 5.1 annotates variables this way:
#Variable amount is the total spending on
#grocery
amount = 3400
#totalMarks is sum of marks in all the tests
#of Mathematics
totalMarks = test1 + test2 + finalTest
Note the two placements a comment can take: a whole line of its own, or (since the rule is "from # to end of line") tacked after a statement:
speed = 60 # in km per hour — ignored by the interpreter
A commented program
Program 5-4 finds the sum of two numbers, with comments stating the program's purpose up front:
#Program: find the sum of two numbers …