Comments
Programs are read not only by computers, but also by people: by your colleagues, and by you yourself a few weeks later, when you no longer remember why you wrote something the way you did. That's why programming languages have comments: notes in the code that the computer ignores.
In Python, a comment starts with a hash #. Everything after it, up to the end of the line, is ignored. A comment can be on a line of its own, or at the end of a line with code:
# Prints the price of two tickets
print(2 * 150) # 150 is the price of one ticketThis prints only:
300For a longer note, use several lines and start each of them with #:
# Author: Tim Novak
# Date: March 8, 2024
print(2 * 150)A good comment says what you can't see in the code at first sight: what a part of the program is for, or why a value is what it is.
Comments are also useful for switching code off for a while without deleting it. Programmers call this commenting out: put # at the start of a line, and the line no longer runs. When you want it back, just delete the #.
print("This line runs.")
# print("This one doesn't.")This prints:
This line runs.Instructions
- 1
At the very top of the program, add a comment that says what the program does, for example
# My shopping list. - 2
You already have chocolate at home. Comment out the line that prints
chocolate, so that the program prints only:Shopping list: bread milk