Defensive Design
A comment is a note written inside a program for the people who read the code. It might explain what a section does, why an approach was chosen, or what an odd-looking value means. Comments are not instructions to the user, and they are not part of the program's logic.
The translator ignores every comment: comments are stripped out before the code runs, so adding, changing or deleting one never alters the program's output or behaviour. A comment exists purely to help a human being understand what is going on.
In Python a comment starts with a hash symbol #. Everything from the # to the end of that line is treated as a comment, so a comment can sit on its own line above the code it describes or at the end of a line of code.
# Work out the price of a cinema trip for a group
number_of_tickets = int(input("How many tickets? "))
ticket_price = 6.50
# Groups of four or more get a 10% discount
if number_of_tickets >= 4:
total = number_of_tickets * ticket_price * 0.9
else:
total = number_of_tickets * ticket_price
print(total) # price after any discountOutput when the user types 3:
How many tickets? 3
19.5
Programs are changed far more often than they are first written. A maintainer — the original programmer months later, or somebody else taking over — must work out what the code was meant to do before safely fixing a bug or adding a feature. Comments that explain a section's purpose make that quicker and reduce the chance of a change breaking something. They help with debugging too, because a note saying what a block should produce makes it easier to spot where it goes wrong.
The best comments explain purpose or logic — the reason behind the code. Weak comments simply repeat what the line already says, or give instructions to a user instead of explaining the code.
# add one to counter above counter = counter + 1, which is already obvious.# type your name below, which instructs the user rather than describing the code.Commenting sits alongside sub programs, meaningful naming conventions and indentation as a way of making a program easier to maintain, but it does not change what the program does.
OCR GCSE Computer Science · Defensive Design