The hash character
Comments are short phrases that explain what the code is doing. Ex: Lines 1, 8, and 10 in the following program contain comments. Each comment begins with a hash character (#). All text from the hash character to the end of the line is ignored when running the program. In contrast, hash characters inside of strings are treated as regular text. Ex: The string “Item #1: ” does not contain a comment.

When writing comments:

  • The # character should be followed by a single space. Ex: # End of menu is easier to read than #End of
  • Comments should explain the purpose of the code, not just repeat the code itself. Ex: # Get the user’s
    preferences is more descriptive than # Input item1 and item2.

Example i:

Program with three comments
1 # Display the menu options
2 print(“Lunch Menu”)
3 print(“———-“)
4 print(“Burrito”)
5 print(“Enchilada”)
6 print(“Taco”)
7 print(“Salad”)
8 print() # End of menu
10 # Get the user’s preferences
11 item1 = input(“Item #1: “)
12 item2 = input(“Item #2: “)

Code quality
The example program above had two parts: (1) display the menu options, and (2) get the user’s preferences.
Together, the blank lines and comments show the overall structure of the program.
Programmers spend more time reading code than writing code. Therefore, making code easier for others to read and understand is important. Two ways to improve code quality include:

  • Separate each part (lines that have a similar purpose) with a blank line.

Python programs may optionally begin with a string known as a docstring. A docstring is documentation written for others who will use the program but not necessarily read the source code. Most of the official documentation at docs.python.org is generated from docstrings.
Documentation can be long, so docstrings are generally written as multi-line strings (“””). Common elements of a docstring include a one-line summary, a blank line, and a longer description.

Leave a Reply